依赖包
c3p0-0.9.1.2.jar
commons-dbutils-1.6.jar
mysql-connector-java-5.1.12-bin.jar
C3P0的配置文件c3p0-config.xml
<c3p0-config>
<!-- c3p0默认配置,下面还可以配置多个数据库 -->
<default-config>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/test
</property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="user">root</property>
<property name="password">123456</property>
<property name="initialPoolSize">6</property>
<property name="maxPoolSize">50</property>
<property name="maxIdleTime">1000</property>
</default-config>
</c3p0-config>
BserUtils类,c3p0和QueryRunner的核心类
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.apache.commons.dbutils.QueryRunner;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class BaseUtils {
//初始化c3p0
private static DataSource dataSource=null;
static{
//自动加载src目录下面的c3p0的配置文件,【c3p0-config.xml】
dataSource = new ComboPooledDataSource();
}
public static QueryRunner getQueryRunner(){
//第一步:创建QueryRunner对象,传入连接池对象
//在创建QueryRunner对象的时候,如果传入数据对象dataSource,
//那么在使用QueryRunner对象的方法时候,就不需要传入连接对象
QueryRunner query=new QueryRunner(dataSource);
//第二步:会自动从数据源中获取连接(不用关闭连接)
return query;
}
/***
* 实现增删改的公共方法
* @param sql
* @param arr
* @return
*/
public static boolean addUpdateDelete(String sql,Object[] arr){
QueryRunner qr=getQueryRunner();
int count;
try {
count = qr.update(sql, arr);
if(count>0){
return true;
}else{
return false;
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
}
在DAO层调用BaseUtils
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.dao.UserDao;
import com.entity.User;
import com.util.BaseUtils;
public class UserDaoImpl implements UserDao{
@Override
public List<User> selectUser() {
//创建QueryRunner
//记住查询是BeanListHandler区别增删改的方法BeanHandler
QueryRunner qr=BaseUtils.getQueryRunner();
try {
String sql="select * from user ";
List<User> list =(List<User>)qr.query(sql, new BeanListHandler(User.class));
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
//如果没用c3p0连接池,而是普通连接方式则稍有变化
@Override
public List<User> selectUser() {
//连接数据库
Connection con = Conn.getConnection;//Conn类在下边
QueryRunner qr=new QueryRunner();
try {
String sql="select * from user ";
List<User> list =(List<User>)qr.query(con,sql, new BeanListHandler(User.class));
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
}
连接数据库
public class Conn{
static Connection conn;
public static Connection getConnection(){
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(ClassNotFoundException e){
e.printStackTrace();
}
try{
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true","root","password");
}catch(SQLException e){
e.printStackTrace();
}
return conn;
}
}
该文有部分内容从其他网站转载,加上自己的一些理解及日常应用整理至此