JdbcUtils工具类

1. JdbcUtils工具类

1.1 连接获取工具类JdbcUtils工具类的创建

之前我们写代码的时候,每个demo中都会有getConnection方法的创建,造成了很大的冗余!

现在我们可以创建一个JdbcUtils工具类,把连接的获取方法放到该类中,每次需要连接都从该类获取!
并且我们可以优化连接获取方法!让其变成一个更加通用的连接获取工具类!
代码演示:

JdbcUtils.java
public class JdbcUtils {

	public static Connection getConnection() {
	     //配置文件位置
         private String dbconfig = "dbconfig.properties";
         //map集合+io流的结合体
	     private Properties prop = new Properties();
	     //输入流
         InputStream in = null;
		try {
             in = new FileInputStream(dbconfig);
			prop.load(in);
		//jdbc四大配置参数:driver类的全路径  ,url , username , password
        Class.forName(prop.getProperty("driverClassName"));
        Connection con = DriverManager.getConnection(
                prop.getProperty("url"),
                prop.getProperty("username"),
                prop.getProperty("password"));
        return con;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}

配置文件 : dbconfig.properties

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mydb1
username=root
password=1234

1.2 连接获取工具类JdbcUtils工具类的优化

public class JdbcUtils {
	private static Properties prop = null;
	//静态代码块,自动加载
	static {
		try {
			prop = new Properties();//集合+io
			InputStream is = new FileInputStream("dbconfig.properties");
			prop.load(is);
			//加载驱动类
			Class.forName(prop.getProperty("driverClassName"));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		 
	}
	public static Connection getConnection() {
		try {
			// 通过驱动管理得到连接对象
			Connection con = DriverManager.getConnection(prop.getProperty("url"), 
					prop.getProperty("username"),prop.getProperty("password") );
			return con;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		
	}
	@Test
	public void test() {
		System.out.println(getConnection());
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值