You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
2.1 KiB
Java

2 years ago
package com.xjgs.dao;
import com.mchange.v2.c3p0.C3P0ProxyConnection;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import javax.sql.DataSource;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCUtils {
//创建数据库连接池对象
private static ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("his");
//获取连接的方法
public static Connection getConnection() throws SQLException {
return comboPooledDataSource.getConnection();
}
//提供数据库连接池对象的方法
public static DataSource getDataSource(){
return comboPooledDataSource;
}
//释放资源的方法
public static void release(ResultSet rs, Statement stmt, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
release(stmt, conn);
}
public static void release(Statement stmt, Connection conn) {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
public static Connection getRawConnection(Connection conn) {
C3P0ProxyConnection cpCon = (C3P0ProxyConnection) conn;
Connection unwrappedCon = null;
try {
Method rawConnectionMethod = JDBCUtils.class.getMethod("getRawConnection", new Class[]{Connection.class});
unwrappedCon = (Connection) cpCon.rawConnectionOperation(rawConnectionMethod, null, new Object[]{C3P0ProxyConnection.RAW_CONNECTION});
} catch (Exception ex) {
//do something }
}
return conn;
}
}