黑马程序员技术交流社区
标题:
DBCP连接池
[打印本页]
作者:
追梦赤子心2580
时间:
2016-12-28 00:25
标题:
DBCP连接池
//方法一;
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;
}
}
//方法二:
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();
}
}
}
作者:
1134323536
时间:
2016-12-28 01:38
谢分享
作者:
月微怜
时间:
2016-12-28 16:09
感谢分享,,受教受教
作者:
袁志娜
时间:
2016-12-30 22:52
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2