Java开发基础-JDBC-基本使用步骤—04

本文介绍了一种利用Java的Properties工具类来管理数据库连接信息的方法,这种方法能够简化代码并提高可维护性。通过实例展示了如何在项目中创建和读取数据库配置文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码改进背景介绍:V2版本

如果将数据库连接信息放在代码中不利于后期的维护与查找,为了解决这个问题,我们可以使用java提供的API工具类:

java.util.Properties来实现。

首先通过下面的简单实例了解如何使这个工具类:

项目结构如下图所示:

1.在resources目录下编写数据库连接属性文件db.properties:【注意:这里使用:与=效果一样】

jdbc.driverclass=oracle.jdbc.driver.OracleDriver
jdbc.url:jdbc:oracle:thin:@localhost:1521:orcl
jdbc.user=learn
jdbc.password=learn
2.编写Properties测试类TestProperties:
/**
 * 演示:Properties工具类读取属性文件
 * @author Cher_du
 *
 */
public class TestProperties {
	
	public static void main(String[] args) throws IOException {
		
		Properties prop =new Properties();
		//获取指向当前项目类路径中属性文件的输入流
	   InputStream inStream	= TestProperties.class.getClassLoader()
			   				  .getResourceAsStream("db.properties");
		
		//加载属性文件数据到内存中
		prop.load(inStream);
		//根据已知的key获取value
		String url = prop.getProperty("jdbc.url");
		System.out.println(url);
	}

}

3.运行程序我们可以看到成功获取到对应属性url信息

正式开工:生气

通过上面对Properties类的简单介绍,下面通过它来改进我们之前的DBUtil工具类:

/**
 * 该类用来管理连接
 * 数据库连接的信息,保存在属性文件中
 * @author Cher_du
 *
 */
public class DBUtil2 {
	
	private static String driverClass;
	private static String url;
	private static String user;
	private static String password;
	
	static{
		
		//加载属性文件数据
		Properties prop = new Properties();
		try {
			prop.load(DBUtil2.class.getClassLoader().getResourceAsStream("db.properties"));
			driverClass = prop.getProperty("jdbc.driverclass");
			url = prop.getProperty("jdbc.url");
			user = prop.getProperty("jdbc.user");
			password = prop.getProperty("jdbc.password");
			
			//1.加载驱动
			Class.forName(driverClass);
		}catch (ClassNotFoundException e) {
			e.printStackTrace();	
			throw new RuntimeException("加载驱动错误!",e);
		}catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException("读取属性文件错误!",e);
		} 
	}
	
	//2.创建连接
	/*如何定义一个创建连接的方法
	 * 
	 * 返回值类型:
	 *    是否有运算结果,如果有,
	 *    结果的类型即为返回值类型。
	 * 参数列表:
	 *    功能中,是否有不确定的数据参与运算
	 *    如果有,即为参数列表
	 */
	public static Connection getConnection() throws SQLException{
		
		Connection conn	= DriverManager.getConnection(url, user, password);
		return conn;
	}
	
	//3.
	public static void  close(Connection conn){
		if(conn !=null){
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException("关闭连接错误!",e);
			}
		}
	}
	
	//测试
	public static void main(String[] args) throws SQLException {
		System.out.println(getConnection());
	}
	
	
}

运行程序可以看到成功获取到数据库连接!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Coder_Boy_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值