avatar

JDBC工具类的编写与调用

封装工具类

为了减少代码工作量,将JDBC注册、获取连接、释放连接封装为一个工具类;
具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
public class JDBCUtils {
private static String url;
private static String user;
private static String password;
private static String driver;
static{
try {
Properties pro = new Properties();
//获取src路径下的文件的方式
ClassLoader classLoader = JDBCUtils.class.getClassLoader();
URL res = classLoader.getResource("jdbc.properties");
String path = res.getPath();
System.out.println(path);
//加载文件
pro.load(new FileReader(path));

url = pro.getProperty("url");
user = pro.getProperty("user");
password = pro.getProperty("password");
driver = pro.getProperty("driver");
Class.forName(driver);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
// 获取连接
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,user,password);
}
//释放连接
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();
}
}
}
//重载close()
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();
}
}
}
}

src 下 jdbc.properties 内容如下:

1
2
3
4
url=jdbc:mysql:///xxx?serverTimezone=UTC 
user=root
password=root
driver=com.mysql.cj.jdbc.Driver

如果你数据库连接默认为 locahost:3306 则可以简写为///+数据库名称,?serverTimezone=UTC 是为了避免时区不同问题;

调用工具类

调用工具类具体实例如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public class JDBCdemo08 {

public static void main(String[] args) {
List<Emp> list = new JDBCdemo08().findAll();
System.out.println(list);
System.out.println(list.size());
}
public List<Emp> findAll(){
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
List<Emp> list = null;
try {
//获取连接
conn = JDBCUtils.getConnection();
//执行sql语句
String sql = "select *from admin";
stmt = conn.createStatement();
//获取返回列表
rs = stmt.executeQuery(sql);
Emp emp = null;
list = new ArrayList<Emp>();
while(rs.next()){
int id = rs.getInt("aid");
String name = rs.getString("aname");
int password = rs.getInt("apassword");
String sex = rs.getString("asex");
int age = rs.getInt("aage");
emp = new Emp();
emp.setId(id);
emp.setName(name);
emp.setSex(sex);
emp.setPassword(password);
list.add(emp);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
JDBCUtils.close(rs,stmt,conn); //释放资源
}
return list;
}

}

评论