Druid是阿里巴巴开源平台上一个数据库连接池实现,它结合了C3P0、DBCP、Proxool等DB池的优点,同时加入了日志监控,可以很好的监控DB池连接和SQL的执行情况,可以说是针对监控而生的DB连接池,据说是目前最好的连接池。
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import javax.sql.DataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
/*
- 此类用于演示使用连接池获取连接的方式,封装JDBCUtils
- 功能:
- 1、获取连接
- 2、释放连接资源
*/
public class JDBCUtilsBYdruid {
static DataSource dds;
static{
try {
Properties properties = new Properties();
properties.load(new FileInputStream(“src\druid.properties”));
dds = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 功能:获取连接
* @return 可用的连接对象
* @throws IOException
* @throws FileNotFoundException
*/
public static Connection getConn(){
try {
Connection connection = dds.getConnection();
return connection;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 释放资源
* @param conn
* @param st
* @param rs
*/
public static void close(ResultSet set,Statement statement,Connection connection){
try {
if(set!=null)
set.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:3306/student?rewriteBatchedStatements=true
#url=jdbc:mysql://localhost:3306/girls
username=root
password=123
initialSize=10
minIdle=5
maxActive=20
maxWait=5000