Druid连接池怎么使用
Druid连接池是一种用于管理和维护Druid数据库连接的工具。Druid是一个开源的分布式数据存储系统,用于处理大规模的实时数据分析。连接池的作用是在应用程序和数据库之间建立和管理连接,以提高数据库访问的效率和性能。通过使用连接池,应用程序可以重复使用已经建立的数据库连接,而不需要每次都重新创建连接,从而减少了连接的开销。连接池还可以限制同时打开的连接数量,以防止数据库被过多的连接请求压垮。总之,Druid连接池是一种优化数据库连接管理的工具,可以提高应用程序与Druid数据库之间的交互效率。
使用Druid连接池时,首先我们需要把相关的jar包导入项目,在Apache官网可以找到自己需要的版本。
文章中使用的是以下版本的jar包:
在有了jar包之后,我们写一个工具类,代码如下:
public class JDBCUtilsByDruid {
private static DataSource ds;
//在静态代码块完成 ds初始化
static {
Properties properties = new Properties();
try {
properties.load(com.bjx.manage.utils.JDBCUtilsByDruid.class.getClassLoader().getResourceAsStream("druid.properties"));
ds = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
//编写getConnection方法
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
//关闭连接,在数据库连接池技术中,close 不是真的断掉连接
//而是把使用的Connection对象放回连接池
public static void close(ResultSet resultSet, Statement statement, Connection connection) {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
我们使用的是配置文件连接数据库,所以我们还需要写一下配置文件
配置如下
#key=value
driverClassName=com.mysql.jdbc.Driver
#数据库地址
url=jdbc:mysql://localhost(ip):3306(端口)/test(数据库名称)?rewriteBatchedStatements=true(支持批量插入语句)
#这个是数据库的用户名(根据实际情况填写)
username=wechat
#这个是数据库的密码
password=root
#initial connection Size
initialSize=10
#min idle connecton size
minIdle=5
#max active connection size
maxActive=50
#max wait time (5000 mil seconds)
maxWait=5000
这样,我们就完成了所有的配置,可以使用Druid数据库连接池连接数据库了。
使用JDBCUtilsByDruid.getConnection(); 即可以得到连接,对数据库进行操作。