2021.12.28----JDBC数据库连接池
有c3p0和bruid(德鲁伊)两个连接池版本
支持阿里巴巴的国产用bruid
导入jar和properties

下面是工具类JDBCUtils
private static DataSource ds;
static {
try {
Properties pro = new Properties();
InputStream is = DruidDemo.class.getClassLoader().getResourceAsStream("druid.properties");
pro.load(is);
ds = DruidDataSourceFactory.createDataSource(pro);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
}
}
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
//释放资源
public static void close(ResultSet rs, Statement stmt, Connection conn) {
if(stmt != null){
try{
stmt.close();
}catch (SQLException s){
s.printStackTrace();
}
}
if (conn != null){
try{
conn.close();
}catch (SQLException s){
s.printStackTrace();
}
}
if (rs != null){
try{
rs.close();
}catch (SQLException s){
s.printStackTrace();
}
}
}
public static void close(Statement stmt, Connection conn) {
if(stmt != null){
try{
stmt.close();
}catch (SQLException s){
s.printStackTrace();
}
}
if (conn != null){
try{
conn.close();
}catch (SQLException s){
s.printStackTrace();
}
}
}
//获取连接池
public static DataSource getDataSouce(){
return ds;
}
主类:
Connection conn = null;
PreparedStatement pstmt = null;
//获取连接
conn = JDBCUtils.getConnection();
String sql = "insert into stu values (?,?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1,"guo");
pstmt.setString(2,"abcd.1234");
int count = pstmt.executeUpdate();
System.out.println(count);
JDBCUtils.close(pstmt,conn);

浙公网安备 33010602011771号