在最近的一段时间写毕业设计,由于本科阶段的毕业设计不是特别大的项目,所以在数据库连接的这一块就使用了JDBC没有使用框架,但是发现一个好的JDBC工具类也不是那么好写,把自己的记录下来以便以后学习和提高
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
*
* @author XX
* @date 2014-1-22下午10:15:04
*
*/
public class DBUtils {
private static final String URL = "jdbc:sqlserver://localhost:1433;DatabaseName=RJ_Thesis";
private static final String DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
private static final String USER ="sa";
private static final String PASW= "sa";
public static ThreadLocal<Connection> threadLocal =new ThreadLocal<Connection>();
static {
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
/*
* 私有的构造函数
*/
private DBUtils() {
}
/**
* 获取数据库的连接
*@author XX
*@date 2014-1-22下午11:51:20
*@return conn
*/
public static Connection getConnection() {
Connection conn = threadLocal.get();
if(conn == null) {
try {
conn = DriverManager.getConnection(URL, USER, PASW);
threadLocal.set(conn);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
return conn;
}
/**
* 释放资源
*@author XX
*@date 2014-1-22下午11:51:42
*/
public static void closeConnection(){
Connection conn = threadLocal.get();
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}finally{
conn=null;
}
threadLocal.set(null);
}
}
}