學習過程中我們經常需要利用jdbcUtils和c3p0連接池結合來操作數據庫,由於數據操作的基本步驟大體一致,所以我們會自己寫一個工具類來提供Datasource,Connection,釋放資源等操作,再次做一個整理。
package cn.wang.customer.utils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class JDBCUtils {
/**
* JDBC工具類 1.提供連接池 2.釋放資源,根據CRUD的實際情況釋放資源方法需要重載
*
*/
private static DataSource dataSource = new ComboPooledDataSource();
/**
* 工具類提供,連接池對象給 QueryRunner(DataSource dataSourece) 根據實際情況:需要事物管理的就是 無參構造
* 不需要事物管理的就是有參構造
*
* @return
*/
public static DataSource getDataSource() {
return dataSource;
}
/**
* 當需要手動控制事物的時候,需要把conn當做參數傳遞給方法, 所以這邊提供一個方法,獲取conn;
*
* @return
*/
public static Connection getConnection() {
try {
return dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e + "獲取連接池失敗");
}
}
/**
* 提供多個重載的方法釋放資源,根據實際情況調用
*
*/
public static void close(Connection conn) {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
conn = null;
}
}
public static void close(Connection conn, Statement stat) {
try {
if (stat != null) {
stat.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
stat = null;
close(conn);
}
}
public static void close(Connection conn, Statement stat, ResultSet res) {
try {
if (res != null) {
res.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
res = null;
close(conn, stat);
}
}
public static void close(PreparedStatement pst) {
try {
if (pst != null) {
pst.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
pst = null;
}
}
}