public class JdbcUtil {
private static final String url = "";
private static final String user = "";
private static final String password = "";
private static ThreadLocal<Connection> threadLocal;
static {
// 创建线程局部变量对象,初始化线程局部变量的描述对象
threadLocal = new ThreadLocal<Connection>();
// 首先加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new RuntimeException("驱动加载失败...");
}
}
// 获取连接方法
public static Connection getConnection() throws SQLException {
Connection conn = threadLocal.get();
if (conn != null) {
return conn;
} else {
conn = DriverManager.getConnection(url, user, password);
threadLocal.set(conn);
return conn;
}
}
// 关闭连接的方法
public static void close() throws SQLException {
Connection conn = threadLocal.get();
if (conn != null && conn.isClosed()) {
conn.close();
// 清除线程中的连接
threadLocal.remove();
}
}
}
private static final String url = "";
private static final String user = "";
private static final String password = "";
private static ThreadLocal<Connection> threadLocal;
static {
// 创建线程局部变量对象,初始化线程局部变量的描述对象
threadLocal = new ThreadLocal<Connection>();
// 首先加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new RuntimeException("驱动加载失败...");
}
}
// 获取连接方法
public static Connection getConnection() throws SQLException {
Connection conn = threadLocal.get();
if (conn != null) {
return conn;
} else {
conn = DriverManager.getConnection(url, user, password);
threadLocal.set(conn);
return conn;
}
}
// 关闭连接的方法
public static void close() throws SQLException {
Connection conn = threadLocal.get();
if (conn != null && conn.isClosed()) {
conn.close();
// 清除线程中的连接
threadLocal.remove();
}
}
}