通过配置文件实现通用的jdbc链接

<span style="font-family:KaiTi_GB2312;font-size:24px;">一般在项目当中,我们要多次与数据库进行交互	</span>

<span style="font-family:KaiTi_GB2312;font-size:24px;">public void testDriver() throws SQLException {
		// 1.创建一个Driver的实例类对象
		Driver driver = new com.mysql.jdbc.Driver();
		// 2.链接的基本准备。
		String url = "jdbc:mysql://localhost:3306/test";
		Properties info = new Properties();
		info.put("user", "root");
		info.put("password", "root");
		// 3.通过driver的connect方法获取链接
		Connection connect = driver.connect(url, info);
		System.out.println(connect);
	}</span>
具体的流程是:

1.创建一个driver的对象

2.定义url和info信息

3.通过driver的connect方法进行连接


下面的是一个通用的方法,在项目根目录下创建一个jdbc.properties配置文件

在配置文件中定义url,user,password,以及driver。

jdbc.properties

<span style="font-family:KaiTi_GB2312;font-size:24px;">driver=com.mysql.jdbc.Driver
jdbcurl=jdbc:mysql://localhost:3306/test
user=root
password=root
</span>
通用的方法:

<span style="font-family:KaiTi_GB2312;font-size:24px;">public Connection getConnection() throws InstantiationException,
			IllegalAccessException, ClassNotFoundException, SQLException,
			IOException {
		String driverclass = null;
		String jdbcurl = null;
		String user = null;
		String password = null;
		
		// 读取路径下的jdbc.properties
		InputStream in = getClass().getClassLoader().getResourceAsStream(
				"jdbc.properties");//加载路径
		Properties properties = new Properties();
		properties.load(in);
		driverclass = properties.getProperty("driver");
		jdbcurl = properties.getProperty("jdbcurl");
		user = properties.getProperty("user");
		password = properties.getProperty("password");

		Driver driver = (Driver) Class.forName(driverclass).newInstance();//反射
		Properties info = new Properties();
		info.put("user", user);
		info.put("password", password);
		Connection conn = driver.connect(jdbcurl, info);
		return conn;
	}</span>

这样就可以不用修改源代码来更改链接信息,只用修改配置文件就可以




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值