JDBCUtils工具类 通过Druid数据库连接池技术使用
JDBCUtils.java
public class JDBCUtils {
private static DataSource ds; //定义成员变量
static{
Properties pro=new Properties();
try {
pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties")); //加载配置文件
ds= DruidDataSourceFactory.createDataSource(pro); //获取DataSource
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException { //获取连接
return ds.getConnection();
}
//释放资源
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();
}
}
}
public static void close(ResultSet rs, Statement stmt, Connection conn){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
JDBCUtils.close(stmt,conn);
}
public static void close(PreparedStatement pstmt, Connection conn){
if(pstmt!=null){
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(ResultSet rs,PreparedStatement pstmt, Connection conn){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
JDBCUtils.close(pstmt,conn);
}
public static DataSource getDataSource(){
return ds;
}
}
配置文件druid.properties