Druid连接池配置
1.导入jar包
druid-1.1.12.jar
2.jdbc.properties
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/ganlion2018?useSSL=false
username=root
password=root
filters=stat
initialSize=5
maxActive=300
#最大等待时间
maxWait=60000
timeBetweenEvictionRunsMillis=60000
minEvictableIdleTimeMillis=300000
validationQuery=SELECT 1
testWhileIdle=true
testOnBorrow=false
testOnReturn=false
poolPreparedStatements=false
3.JDBCUtils.java
package util;
import java.sql.Connection;
import java.sql.PreparedStatement;
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;
import org.apache.commons.dbutils.QueryRunner;
/**
* {Druid连接池工具类}
*
* @author Tang
*/
public class JDBCUtils {
// 1.定义成员变量DataSource
private static DataSource dataSource;
static {
try {
// 2.加载配置文件
Properties properties = new Properties();
properties.load(JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties"));
// 3.获取DataSource
dataSource = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* {获得连接}
*/
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
/**
* 获得连接池方法
*/
public static DataSource getDataSource() {
return dataSource;
}
/**
* {获得rueryRunner}
*/
public static QueryRunner getQueryRunner() {
QueryRunner runner = new QueryRunner(dataSource);
return runner;
}
/**
* {释放资源}
*/
public static void close(Statement stmt, Connection conn) {
close(null, stmt, conn);
}
/**
* {释放资源}
*/
public static void close(PreparedStatement stmt, Connection conn) {
close(null, stmt, conn);
}
/**
* {释放资源}
*/
public static void close(ResultSet rs, Statement stmt, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
/**
* {释放资源}
*/
public static void close(ResultSet rs, PreparedStatement stmt, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
}