准备工作:导入需要的包c3p0-0.9.1.2.jar,commons-dbutils-1.4.jar,commons-io-2.2.jar,commons-pool-1.5.6.jar,mysql-connector-java-5.0.8-bin.jar
其次需要导入配置文件c3p0-config.xml
然后开始编写工具类,里边包含连接数据可的方法,开启事务,提交事务,回滚事务的方法,以及关闭资源的方法,代码如下:
package com.qf.utils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.mchange.v2.c3p0.ComboPooledDataSource;
//从连接池中获取连接
//获取连接池子对象
//获取连接
//关闭资源
public class DataSourceUtiles {
private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
//返回连接池对象的方法
private static ThreadLocal<Connection> th= new ThreadLocal<Connection>();
public static ComboPooledDataSource getDataSource() {
return dataSource;//出问题的地方
//写的时候,自己调自己,造成内存溢出
}
public static Connection getConnection() {
Connection connection = th.get();
if(connection==null){
try {//连接池中获取连接的方法
connection = dataSource.getConnection();
th.set(connection);//这儿做了一次修改,原来是th.set(getconnection());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return connection;
}
//开启事务
public static void startTransaction(){
try {
getConnection().setAutoCommit(false);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//提交事务
public static void commit(){
try {
getConnection().commit();
getConnection().close();
th.remove();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//回滚事务
public static void rollback(){
try {
getConnection().rollback();
getConnection().close();
th.remove();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//关闭资源的方法
public static void close(Connection connection) {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void close(ResultSet set) {
if (set != null) {
try {
set.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void close(Statement statement) {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void close(Connection connection, Statement statement) {
close(connection);
close(statement);
}
public static void close(Connection connection, ResultSet set) {
close(connection);
close(set);
}
public static void close(Statement statement, ResultSet set) {
close(statement);
close(set);
}
public static void close(Connection connection, Statement statement, ResultSet set) {
close(connection);
close(statement);
close(set);
}
}