-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJDBCUtils.java
More file actions
100 lines (85 loc) · 2.47 KB
/
Copy pathJDBCUtils.java
File metadata and controls
100 lines (85 loc) · 2.47 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package jdbc.util;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;
/**
* @author : CodeWater
* @create :2022-03-09-11:03
* @Function Description :jdbc工具类
*/
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();
ClassLoader classLoader = JDBCUtils.class.getClassLoader();
URL res = classLoader.getResource("jdbc.properties");
String path = res.getPath();
//加载文件
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();
}
}
}
/*释放资源,多个ResultSet
* */
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();
}
}
}
}