首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >JDBC工具类-JdbcUtils

JDBC工具类-JdbcUtils

作者头像
星哥玩云
发布于 2022-09-14 20:48:28
发布于 2022-09-14 20:48:28
8670
举报
文章被收录于专栏:开源部署开源部署

一、JdbcUtils的作用

前面我们学了,连接数据库的四大参数是:驱动类、url、用户名,以及密码。这些参数都与特定数据库关联,如果将来想更改数据库,那么就要去修改这四大参数,那么为了不去修改代码,我们写一个JdbcUtils类,让它从配置文件中读取配置参数,然后创建连接对象。

二、JdbcUtils代码

JdbcUtils.java

代码语言:javascript
复制
public class JdbcUtils {
	private static final String dbconfig = "dbconfig.properties" ;
	private static Properties prop = new Properties() ;
	static {
		try {
			InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(dbconfig);
			prop.load(in);
			Class.forName(prop.getProperty("driverClassName"));
		} catch(IOException e) {
			throw new RuntimeException(e);
		}
	} 

	public static Connection getConnection () {
		try {
			return DriverManager.getConnection(prop.getProperty("url"),
					prop.getProperty("username"), prop.getProperty("password"));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}

dbconfig.properties

代码语言:javascript
复制
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mydb1
username=root
password=123
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除
目录
  • 一、JdbcUtils的作用
  • 二、JdbcUtils代码
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档