DBCP连接池
Posted 情镌三分木,相思万骨书
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了DBCP连接池相关的知识,希望对你有一定的参考价值。
方法一:
package DBCPUtils;
import java.util.List;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
public class DBCPUtils {
public static void main(String[] args) {
try {
// 读取配置文件
Properties properties = new Properties();
properties.load(DBCPUtils.class.getClassLoader()
.getResourceAsStream("jdbc.properties"));
// 从连接池中获取连接对象
DataSource dataSource = BasicDataSourceFactory
.createDataSource(properties);
String sql = "select * from emp";
QueryRunner qr = new QueryRunner(dataSource);
List<Object[]> list = qr.query(sql, new ArrayListHandler());
for (Object[] objects : list) {
for (Object object : objects) {
System.out.print(object + "\t");
}
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
方法二:
package DBUtils;
import java.io.InputStream;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
public class DBUtils {
private static String DriverClass;
private static String url;
private static String username;
private static String password;
private static BasicDataSource dataSource = new BasicDataSource();
static {
loadRead();
dataSource.setDriverClassName(DriverClass);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
}
private static void loadRead() {
try {
InputStream in = DBUtils.class.getClassLoader()
.getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(in);
DriverClass = properties.getProperty("DriverClass");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
} catch (Exception e) {
e.printStackTrace();
}
}
public static DataSource getDataSource(){
return dataSource;
}
}
以上是关于DBCP连接池的主要内容,如果未能解决你的问题,请参考以下文章