C3P0工具类,XML文件中写关于数据库的一些配置信息
package com.itheima.utils;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class C3P0utilsXML {
//C3P0连接池特有的,创捷一个工具类需要使用XML配置文件
//把c3p0-config.xml复制到当前模块day03的src下边(名字不能改变,xml文件里边的内容格式也不能改变)
//C3P0会自动读取该文件,使用连接池的配置信息给C3P0的对象赋值
private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
//连接池的配置信息会自动从XML文件中读取
//创捷静态方法得到一个数据量连接对象
public static Connection getConnection(){
try {
return dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException("获取数据库连接失败"+e);
}
}
//创捷静态方法,释放资源
public static void close(Connection conn, Statement stat, ResultSet rs){
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stat != null){
try {
stat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
使用C3P0实现对数据库的操作
package com.itheima.c0p3Test;
import com.itheima.utils.C3P0utilsXML;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class C0P3Test {
public static void main(String[] args) throws SQLException {
test02();
}
private static void test02() throws SQLException {
//从C3P0连接池中获取数据库连接对象
Connection conn = C3P0utilsXML.getConnection();
//获取预编译执行对象
String sql = "select * from users where uid in(?,?)";
PreparedStatement pst = conn.prepareStatement(sql);
pst.setObject(1,2);
pst.setObject(2,3);
//执行sql语句,获取结果
ResultSet rs = pst.executeQuery();
//处理结果
while(rs.next()){
String username = rs.getString("username");
String password = rs.getString("password");
System.out.println(username+"\t"+password);
}
//释放资源
C3P0utilsXML.close(conn,pst,rs);
}
}