Druid 数据库连接池

时间:2023-11-16 19:39:56
druid   数据库连接池   由阿里提供
步骤
1 导包 durid1.0.9 jar 包
2 定义配置文件 必须是 properties文件 名字任意 位置也任意
3 获得数据库连接池对象 通过 DuridDataSourceFactory获得
4 获取连接
具体代码如下
package Demo3Durid; import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.util.Properties; public class Demo3Durid {
public static void main(String[] args) throws Exception {
//加载文件
Properties pro=new Properties();
InputStream in = Demo3Durid.class.getClassLoader().getResourceAsStream("druid.properties");
pro.load(in);
//获得连接池对象 通过 DuridDataSourceFactory获得
DataSource ds = DruidDataSourceFactory.createDataSource(pro);
//获取连接
Connection conn = ds.getConnection();
System.out.println(conn); } }
利用工具类 实现  Druid连接池
package JdbcUtils; import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties; /*
*Druid工具类
**/
public class JdbcUtils {
//定义成员变量 DateSource
private static DataSource ds; static{
//加载配置文件
try {
Properties pro=new Properties();
InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("druid.properties");
pro.load(in);
ds = DruidDataSourceFactory.createDataSource(pro); } catch (Exception e) {
e.printStackTrace();
} }
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
//释放资源
public static void close(AutoCloseable... c){
for(AutoCloseable a: c){
if(a!=null){
try {
a.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
} } 连接
package JdbcUtils; import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException; public class Demo4Druid { private static PreparedStatement ps;
private static Connection conn; public static void main(String[] args) {
//完成一个添加操作 try {
//获得连接
conn = JdbcUtils.getConnection();
//定义sql语句
String sql="insert into coount values(null,?,?)";
//获得执行语句
ps = conn.prepareStatement(sql);
//给?赋值
ps.setString(1,"李登");
ps.setDouble(2,20000);
//执行sql
int i = ps.executeUpdate();
System.out.println(i); } catch (SQLException e) {
e.printStackTrace();
}finally {
JdbcUtils.close(ps,conn);
}
}
}