使用步骤(使用到的jar包都在文末)
代码示例
url = jdbc:mysql://localhost:3306/test
username = root
password = root
import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
public class C3P0Example {
// 创建一个数据库连接池对象
private static ComboPooledDataSource dataSource;
// 静态代码块
static{
// 加载配置文件到内存中
Properties pro = new Properties();
try {
pro.load(C3P0Example.class.getClassLoader().getResourceAsStream("c3p0.properties"));
} catch (IOException e) {
e.printStackTrace();
}
// 配置 c3p0 连接池
dataSource = new ComboPooledDataSource();
dataSource.setJdbcUrl(pro.getProperty("url"));
dataSource.setUser(pro.getProperty("username"));
dataSource.setPassword(pro.getProperty("password"));
}
public static Connection getConnection() throws SQLException {
// 从连接池获取 数据库连接对象
return dataSource.getConnection();
}
public static void main(String[] args) {
Connection con = null;
try {
// 获取数据库连接对象
con = getConnection();
// 定义sql语句
String sql = "SELECT * FROM account WHERE id = ?";
// 获取执行 SQL 对象
PreparedStatement pst = con.prepareStatement(sql);
// 填充占位符
pst.setInt(1,2);
// 执行 SQL
ResultSet rs = pst.executeQuery();
// 输出结果
while(rs.next()){
int id = rs.getInt(1);
String name = rs.getString(2);
double balance = rs.getDouble(3);
System.out.println(id+"--"+name+"--"+balance);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
if(con != null){
try {
// 将连接返回给 连接池
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
使用步骤
示例代码
url = jdbc:mysql://localhost:3306/test
username = root
password = root
public class DruidExample {
// 创建一个数据库连接池对象
private static DruidDataSource ds;
// 静态代码块
static{
try {
// 加载配置文件到内存中
Properties pro = new Properties();
InputStream is = DruidExample.class.getClassLoader().getResourceAsStream("druid.properties");
pro.load(is);
// 配置 druid 连接池
ds = (DruidDataSource) DruidDataSourceFactory.createDataSource(pro);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
// 从连接池获取 数据库连接对象
return ds.getConnection();
}
public static void main(String[] args) {
Connection con = null;
try {
// 获取数据库连接对象
con = getConnection();
// 定义sql语句
String sql = "SELECT * FROM account WHERE id = ?";
// 获取执行 SQL 对象
PreparedStatement pst = con.prepareStatement(sql);
// 填充占位符
pst.setInt(1,2);
System.out.println(1);
// 执行 SQL
ResultSet rs = pst.executeQuery();
// 输出结果
while(rs.next()){
int id = rs.getInt(1);
String name = rs.getString(2);
double balance = rs.getDouble(3);
System.out.println(id+"--"+name+"--"+balance);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
if(con != null){
try {
// 将连接返回给 连接池
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}