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());
}
}