-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConnUtil.java
46 lines (41 loc) · 1.28 KB
/
ConnUtil.java
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
package com.Utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnUtil extends ThreadLocal{
private static String name = "root";
private static String pwd = "password";
private static String url = "jdbc:mysql://localhost:3306/ood?useOldAliasMetadataBehavior=true";
private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();
private static Connection createConn() {
try {
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection(url, name, pwd);
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
public static Connection getConn() {
Connection conn = threadLocal.get();
if(conn == null) {
threadLocal.set(createConn());
conn = threadLocal.get();
}
return conn;
}
public static void close() {
Connection conn = threadLocal.get();
if(conn == null) {
return;
}
try {
if(!conn.isClosed()) {
conn.close();
threadLocal.remove();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}