c3p0工具类,使用了xml配置文件
package com.dbsy.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 {
private static ComboPooledDataSource dataSource =new ComboPooledDataSource();
public static Connection getConnection(){
try {
return dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException("获取数据库连接对象失败:"+e);
}
}
public static void close(ResultSet rs, Statement stat,Connection conn){
if (rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stat!=null){
try {
stat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
package com.dbsy.test;
import com.dbsy.utils.C3P0Utils;
import com.dbsy.utils.C3P0UtilsXML;
import java.sql.*;
public class Demo01TestC3P0Utils {
public static void main(String[] args) throws SQLException {
test2();
}
private static void test2() throws SQLException {
Connection conn = C3P0UtilsXML.getConnection();
PreparedStatement pst = conn.prepareStatement("select * from users where uid in(?,?,?)");
pst.setObject(1,1);
pst.setObject(2,2);
pst.setObject(3,3);
ResultSet rs = pst.executeQuery();
while (rs.next()){
int uid = rs.getInt("uid");
String username = rs.getString("username");
String password = rs.getString("password");
System.out.println(uid+"\t"+username+"\t"+password);
}
C3P0UtilsXML.close(rs,pst,conn);
}
private static void test1() throws SQLException {
Connection conn = C3P0Utils.getConnection();
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery("select * from users");
while (rs.next()){
int uid = rs.getInt("uid");
String username = rs.getString("username");
String password = rs.getString("password");
System.out.println(uid+"\t"+username+"\t"+password);
}
C3P0Utils.close(rs,stat,conn);
}
}