81,094
社区成员
发帖
与我相关
我的任务
分享
public class JdbcUtil {
private static final String url = "jdbc:mysql://localhost:3306/dbdemo?useUnicode=true&characterEncoding=UTF-8";
private static final String user = "root";
private static final String password = "sa";
private static ThreadLocal<Connection> connectionContainer = new ThreadLocal<Connection>();
/**
* 注册
*
* @throws ClassNotFoundException
* @throws SQLException
*/
public static Connection register() {
Connection connection = connectionContainer.get();
try {
if (connection == null) {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
connection = DriverManager.getConnection(url, user, password);
}
connectionContainer.set(connection);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return connection;
}
public static void freeResource(Statement statement, ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
if (statement != null) {
statement.close();
}
Connection connection = connectionContainer.get();
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
connectionContainer.remove();
}
}
}