public class JDBCUtil {public static DataSource ds = null;
static {//这一块static要在上面static下,不能变换位置,若变换,则上面无法静态执行
//[1]连接池方式启动驱动
try {
Properties p = new Properties();
InputStream in = JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties");
System.out.println(in);
p.load(in);
//德鲁伊Druid方式连接池
ds = DruidDataSourceFactory.createDataSource(p);
} catch (Exception e) {
e.printStackTrace();
}
}
//获取数据源
public static DataSource getDataSource(){
return ds;
}
public static Connection getConn(){
try {
//[2]德鲁伊Druid连接池连接对象
return ds.getConnection();
}catch (Exception e){
e.printStackTrace();
}
return null;
}
//释放资源
public static void close(Connection conn, Statement st, ResultSet rs){
//[5]释放资源
if (rs != null){
try {
rs.close();//关闭ResultSet接口
} catch (SQLException e) {
e.printStackTrace();
System.out.println("ResultSet接口关闭失败");
}
}
if (st != null){
try {
st.close();//关闭statement接口
} catch (SQLException e) {
e.printStackTrace();
System.out.println("Statement接口关闭失败");
}
}
if (conn != null){
try {
conn.close();//关闭Connection接口
} catch (SQLException e) {
e.printStackTrace();
System.out.println("Connection接口关闭失败");
}
}
}
数据库连接
最新推荐文章于 2023-11-29 09:51:56 发布