整合c3p0连接池
需要3个jar包
1.、c3p0-0.9.5.2.jar、mysql-connector-java-5.1.40.jar、mchange-commons-java-0.2.11.jar
2.引入jar包后用c3p0连接池整合jdbc
1.创建C3p0连接池
//1.创建c3p0连接池
ComboPooledDataSource pool = new ComboPooledDataSource();
2.设置连接信息
|
V
1.设置用户名
pool.setUser("root");//MySql账号
2.设置密码
pool.setPassword("123456");//MySql密码
3.设置jdbcurl
pool.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/mayikt");//设置jdbcurl
4.设置加载驱动
pool.setDriverClass("com.mysql.jdbc.Driver");//设置加载驱动
3.获取连接对象
//3.获取连接对象
Connection connection = pool.getConnection();
4.编写sql语句
//编写sql语句
String selectUserSql="select id,phone,pwd from mayikt_users where id=?";
5.获取预编译执行者对象,防止sql注入问题
//4.获取预编译执行者对象,防止sql注入的问题
PreparedStatement preparedStatement =connection.prepareStatement(selectUserSql);
6.执行sql语句
ResultSet resultSet = preparedStatement.executeQuery();//执行sql语句
7.关闭资源
//关闭连接
connection.close();
preparedStatement.close();
测试完整代码
需要有对应的实体类
package com.shxy.test;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mchange.v2.c3p0.PooledDataSource;
import com.shxy.entity.User;
import org.junit.Test;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Test01 {
@Test
public void test01() throws PropertyVetoException, SQLException {
//1.创建c3p0连接池
ComboPooledDataSource pool = new ComboPooledDataSource();
//2.设置连接信息
pool.setUser("root");//MySql账号
pool.setPassword("123456");//MySql密码
pool.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/mayikt");//设置jdbcurl
pool.setDriverClass("com.mysql.jdbc.Driver");//设置加载驱动
//3.获取连接对象
Connection connection = pool.getConnection();
//编写sql语句
String selectUserSql="select id,phone,pwd from mayikt_users where id=?";
//4.获取预编译执行者对象,防止sql注入的问题
PreparedStatement preparedStatement =connection.prepareStatement(selectUserSql);
preparedStatement.setInt(1,6);//传入预编译对象参数
ResultSet resultSet = preparedStatement.executeQuery();//执行sql语句
boolean result = resultSet.next();
if(result){
Integer id=resultSet.getInt("id");
String phone=resultSet.getString("phone");
String pwd=resultSet.getString("pwd");
User user =new User(id,phone,pwd);
System.out.println(user);
}
//关闭连接
connection.close();
preparedStatement.close();
}
}