Druid连接池配置
1.步骤
导入jar包 druid-1.0.9.jar和数据库驱动jar包 jar包 提取码:sk8x 复制jar包到项目的libs目录下。右键–>Add As Library 定义配置文件: * 是properties形式的
driverClassName= com. mysql. jdbc. Driver
url= jdbc: mysql: / / 127.0 .0 .1 : 3306 / test
username= root
password= 123456
# 初始化连接数量
initialSize= 5
# 最大连接数量
maxActive= 10
# 超时时间
maxWait= 3000
加载配置文件。
Properties pro = new Properties ( ) ;
InputStream is = DruidDemo. class . getClassLoader ( ) . getResourceAsStream ( "druid.properties" ) ;
pro. load ( is) ;
获取数据库连接池对象:
DataSource ds = DruidDataSourceFactory. createDataSource ( pro) ;
获取连接
Connection con = ds. getConnection ( ) ;
工具类
public class DruidUtils {
private static DataSource ds ;
static {
try {
Properties pro = new Properties ( ) ;
pro. load ( JDBCUtils. class . getClassLoader ( ) . getResourceAsStream ( "druid.properties" ) ) ;
ds = DruidDataSourceFactory. createDataSource ( pro) ;
} catch ( IOException e) {
e. printStackTrace ( ) ;
} catch ( Exception e) {
e. printStackTrace ( ) ;
}
}
public static Connection getConnection ( ) throws SQLException {
return ds. getConnection ( ) ;
}
public static void close ( Statement 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) {
e. printStackTrace ( ) ;
}
}
if ( stmt != null) {
try {
stmt. close ( ) ;
} catch ( SQLException e) {
e. printStackTrace ( ) ;
}
}
if ( conn != null) {
try {
conn. close ( ) ;
} catch ( SQLException e) {
e. printStackTrace ( ) ;
}
}
}
public static DataSource getDataSource ( ) {
return ds;
}
}