JDBC技术进阶
抽取JDBC工具类:JDBCutils
目的:简化书写
分析:
1.注册驱动抽取
2.抽取一个方法获取连接对象
*需求:不想传递参数(麻烦),还得保证工具类的通用性。
*解决:配置文件
代码:
配置文件:jdbc . properties
url=jdbc:mysql:///Test
user=root
password=123456
Driver=com.mysql.cj.jdbc.Driver
工具类:JDBCutils
package com.idea.Test;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;
public class JDBCutils {
private static String url;
private static String user;
private static String password;
private static String Driver;
//获取properties配置文件的内容
static {
try {
Properties pro = new Properties();
ClassLoader classLoader = JDBCutils.class.getClassLoader();
URL resource = classLoader.getResource("pro.properties");
String path = resource.getPath();
pro.load(new FileReader(path));
url = pro.getProperty("url");
user = pro.getProperty("user");
password = pro.getProperty("password");
Driver = pro.getProperty("Driver");
try {
Class.forName(Driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
//获取连接方法
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,user,password);
}
//释放资源方法
public static void close(ResultSet rs,Statement stmt,Connection conn){
if (rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//释放资源方法重载
public static void close(Statement stmt,Connection conn){
if (stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
测试类:
package com.idea.Test;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class JDBC {
public static void main(String[] args) {
List<Emp> list = findAll();
System.out.println(list);
}
public static List<Emp> findAll(){
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
List<Emp> list = null;
try {
conn = JDBCutils.getConnection();
String sql = "select * from emp";
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
Emp emp = null;
list = new ArrayList<>();
while (rs.next()){
int id = rs.getInt(1);
String name = rs.getString("name");
int salary = rs.getInt(3);
Date join_date = rs.getDate(4);
emp = new Emp();
emp.setId(id);
emp.setName(name);
emp.setSalary(salary);
emp.setJoin_time(join_date);
//装载集合
list.add(emp);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
JDBCutils.close(rs,stmt,conn);
}
return list;
}
}
运行结果: