1.先导入c3p0的jar包
(1)MYSQL连接jar包:https://pan.baidu.com/s/1YgK61Yrtadx9mNH7EOrFjg
(2)c3p0相关jar包:https://pan.baidu.com/s/1R-HiQIofGx1gYARI0gZh_A
2.然后配置c3p0配置文件,将c3p0-config.xml配置文件放在src目录下,配置文件的内容如下:
<?xml version="1.0" encoding="utf-8"?>
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/internship?useUnicode=true&characterEncoding=utf-8</property>
<property name="user">root</property>
<property name="password">123789</property>
<property name="initialPoolSize">5</property>
<property name="maxPoolSize">10</property>
<property name="checkoutTimeout">3000</property>
</default-config>
<named-config name="otherc3p0">
</named-config>
</c3p0-config>
3.编写JDBCUtil类
package com.liuliu.util;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JDBCUtil {
private static ComboPooledDataSource data = new ComboPooledDataSource();
public static Connection getConn() {
try {
return data.getConnection();
}catch (SQLException e) {
throw new RuntimeException(e);
}
}
//QueryRunner是Dbutils的核心类之一,它显著的简化了SQL增删查改
public static QueryRunner getQueryRunner(){
QueryRunner queryRunner = new QueryRunner(data);
return queryRunner;
}
public static void close(PreparedStatement pstate) {
try {
pstate.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void close(Connection conn) {
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
4.可在DaoImpl中使用JDBCUtil了,例如,查询用户的所有信息功能
public User findUser(User loginuser) {
//使用JDBC操作数据库
Connection connection = null;
PreparedStatement preparedStatement = null;
User user = null;
ResultSet resultSet = null;
try {
connection = JDBCUtil.getConn();
preparedStatement = connection.prepareStatement("select * from user where username=? and password=? and role=?");
preparedStatement.setString(1,loginuser.getUsername());
preparedStatement.setString(2, loginuser.getPassword());
preparedStatement.setString(3, loginuser.getRole());
resultSet = preparedStatement.executeQuery();
while(resultSet.next()){
user = new User();
user.setUsername(resultSet.getString("username"));
user.setPassword(resultSet.getString("password"));
user.setRole(resultSet.getString("role"));
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return user;
}
c3p0的基本使用就到这里就结束了。