使用第三方工具类创建连接池
用到的jar包:
dbcp2 2.11
dbutils 1.6
logging 1.2
pool2 2.42
首先创建配置文件datasource.properties
#必要选项
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mydatabase
username=root
password=123
#可选项
initialSize=10
maxTotal=8
maxIdle=5
minIdle=1
#最大等待时间
maxWaitMillis=60000
#事物隔离级别(可重复读)
defaultTransactionIsolation=REPEATABLE_READ
下面创建DataSourceUtils连接池工具类
读取配置文件
package DataSourceDemo;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
import javax.sql.DataSource;
import java.io.InputStream;
import java.util.Properties;
/**
* 链接池工具类
* Created by Aongi on 2017/5/2.
* Version 1.0
*/
public class DataSourceUtils {
private static BasicDataSource dataSource;
static{
InputStream in = DataSourceUtils.class.getResourceAsStream("datasource.properties");
Properties pro = new Properties();
try {
pro.load(in);
in.close();
dataSource= BasicDataSourceFactory.createDataSource(pro);
}catch (Exception e){
e.printStackTrace();
throw new RuntimeException("数据库连接失败!");
}
}
public static DataSource getDataSource(){
return dataSource;
}
}
创建测试类,测试连接池工具类
package DataSourceDemo;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import java.sql.SQLException;
import java.util.List;
/**
* 测试工具类
* Created by Aongi on 2017/5/2.
* Version 1.0
*/
public class DataSourceDemo {
private static QueryRunner qr =new QueryRunner(DataSourceUtils.getDataSource());
public static void main(String[] args) {
insert();
select();
}
/**
* 查询数据库信息并遍历
*/
public static void select(){
String sql = "SELECT * FROM users";
try {
List<Object[]> list = qr.query(sql, new ArrayListHandler());
for (Object[] objs : list) {
for (Object obj : objs) {
System.out.print(obj + "\t");
}
System.out.println();
}
}catch (SQLException ex){
throw new RuntimeException("数据添加失败!");
}
}
/**
* 添加数据到数据库
*/
public static void insert(){
String sql = "INSERT INTO users (uname,uaddress,age) VALUES (?,?,?);";
Object[] obj ={"小x","chongqing","23"};
try {
int i = qr.update(sql, obj);
System.out.println(i+"条语句添加成功!");
}catch (SQLException ex){
throw new RuntimeException("数据添加失败!");
}
}
}