zoukankan      html  css  js  c++  java
  • 004-C3P0连接池工具类模板

    package ${enclosing_package};
    
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    
    import javax.sql.DataSource;
    
    import com.mchange.v2.c3p0.ComboPooledDataSource;
    
    public class ${primary_type_name} {
    
        // 1 获得Connection ----- 从连接池中获取
        private static DataSource dataSource = new ComboPooledDataSource();
    
        // 2 创建ThreadLocal 存储的类型是Connection
        private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
    
        // 3 直接可以获取一个连接池
        public static DataSource getDataSource() {
            return dataSource;
        }
        // 4 直接获取一个连接
        public static Connection getConnection() throws SQLException{
            return dataSource.getConnection();
        }
    
        // 5 获取绑定到ThreadLocal上的连接对象
        public static Connection getCurrentConnection() throws SQLException {
            //从ThreadLocal寻找 当前线程是否有对应Connection
            Connection con = tl.get();
            if (con == null) {
                //获得新的connection
                con = dataSource.getConnection();
                //将conn资源绑定到ThreadLocal(map)上
                tl.set(con);
            }
            return con;
        }
    
        // 6 开启事务
        public static void startTransaction() throws SQLException {
            Connection con = getCurrentConnection();
            if (con != null) {
                con.setAutoCommit(false);
            }
        }
    
        // 7 事务回滚
        public static void rollback() throws SQLException {
            Connection con = getCurrentConnection();
            if (con != null) {
                con.rollback();
            }
        }
    
        //  8 提交并且 关闭资源及从ThreadLocall中释放
        public static void commitAndRelease() throws SQLException {
            Connection con = getCurrentConnection();
            if (con != null) {
                con.commit(); // 事务提交
                con.close();// 关闭资源
                tl.remove();// 从线程绑定中移除
            }
        }
    
        // 9 关闭资源方法
        public static void close(ResultSet rs,Statement st,Connection con) throws SQLException {
            if (rs != null) {
                rs.close();
            }
            if (st != null) {
                st.close();
            }
            if (con != null) {
                con.close();
            }
        }
    }
  • 相关阅读:
    if __name__ == '__main__' 用法理解
    VSCode 使用
    sys.argv用法简介
    [Python3] RSA的加解密和签名/验签实现 -- 使用pycrytodome
    python requests 超时与重试
    collections模块之defaultdict()与namedtuple()方法简单介绍
    setdefault函数的用法及理解
    python并发编程之IO模型 同步 异步 阻塞 非阻塞
    django+uWSGI+nginx的工作原理流程与部署过程
    Nginx静态服务配置---详解root和alias指令
  • 原文地址:https://www.cnblogs.com/jepson6669/p/8302345.html
Copyright © 2011-2022 走看看