一、创建一个数据库连接池
- 首先建立工程chaper03,然后在
src
目录下创建xml文件
- 该文件中定义了数据的密码的属性,用于连接数据库
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<named-config name="qfedu">
<propertyname="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl" >jdbc:mysql:192.168.1.9:3306?encodingCharacter=utf8&//</property>
<property name="user">root</property>
<property name="password">nicaibudao</property>
<property name="acquireIncrement">5</property>
<property name="initialPoolSize">20</property>
<property name="minPoolSize">10</property>
<property name="maxPoolSize">40</property>
<property name="maxStatement">0</property>
<property name="maxStatementPerConnection">5</property>
</named-config>
</c3p0-config>
- 然后创建一个
com.qfedu.utils
的包,创建一个工具类C3P0Utils,用于连接数据库等操作
package com.qfedu.utils;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class C3P0Utils {
private static ComboPooledDataSource dataSource = new ComboPooledDataSource("qfedu");
public static DataSource getDataSource() {
return dataSource;
}
}
package com.qfedu.test;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ColumnListHandler;
import com.qfedu.utils.C3P0Utils;
public class TestDBUtils_ColumnListHandler {
public static void main(String[] args) throws SQLException{
QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
String sql = "select * from students";
List<Object> list = (List<Object>) queryRunner.query(sql, new ColumnListHandler("s_name"));
System.out.println(list);
}
}
二、源码: