配置文件 db_dbcp.properites
driverClass=com.mysql.jdbc.Driver url=jdbc:mysql://127.0.0.1:3306/db?useSSL=true username=root password=123456
DBCP連接池工具類 DBCPUtils.java
package top.try51.utils; import java.io.InputStream; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; import javax.sql.DataSource; import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; import org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory; public class DBCPUtils { // 加載名稱為mysqlConn 的配置(src下放置 db_dbcp.properties 配置文件) private static BasicDataSource ds = null; /** * 定義一個ThreadLocal,綁定Connection,每個線程對應一個Connection,執行事務使用 */ private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>(); static { Properties props = new Properties(); try { // 1.加載Properties文件輸入流 InputStream is = DBCPUtils.class.getClassLoader().getResourceAsStream("db_dbcp.properites"); // 2.加載載配置 props.load(is); is.close(); // 3. 創建數據源 ds = BasicDataSourceFactory.createDataSource(props); } catch (Exception e) { throw new RuntimeException(e); } } /** * * @return BasicDataSource */ public static DataSource getDataSource() { return ds; } /** * * @return 由BasicDataSource創建的 Connection */ public static Connection getConnection() { try { return ds.getConnection(); } catch (SQLException e) { throw new RuntimeException(e); } } /** * * @return 獲取當前線程綁定的Connection * @throws SQLException */ public static Connection getTranConnection() throws SQLException{ //得到ThreadLocal中的connection Connection conn = tl.get(); //判斷conn是否為空,如果不為空,則說明事務已經開啟 if(conn == null){ conn = getConnection(); //把當前開啟的事務放入ThreadLocal中 tl.set(conn); } return conn; } /** * 開啟事務,如果當前線程中沒有Connection,則創建該線程對應的一個Connection * @throws SQLException */ public static void beginTran() throws SQLException { //設置事務提交為手動 getTranConnection().setAutoCommit(false); } /** * 提交事務 * @throws SQLException */ public static void commit() throws SQLException { //得到ThreadLocal中的connection Connection conn = getTranConnection(); //判斷conn是否為空,如果為空,則說明沒有開啟事務 if(conn != null){ //如果conn不為空,提交事務 conn.commit(); //事務提交后,關閉連接 conn.close(); //將連接移出ThreadLocal tl.remove(); } } /** * 回滾事務 * @throws SQLException */ public static void rollback() throws SQLException { //得到ThreadLocal中的connection Connection conn = getTranConnection(); //判斷conn是否為空,如果為空,則說明沒有開啟事務,也就不能回滾事務 if(conn != null){ //事務回滾 conn.rollback(); //事務回滾后,關閉連接 conn.close(); //將連接移出ThreadLocal tl.remove(); } } }