zoukankan      html  css  js  c++  java
  • c3p0连接池封装

    在处理数据库事物时需要同一个Connection  但是dbcp无法获得  单独工具也显得繁琐,改进成c3p0工具类:

    package utils;

    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 DataSourceUtils {

    private static DataSource dataSource = new ComboPooledDataSource();

    private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();

    // 直接可以获取一个连接池
    public static DataSource getDataSource() {
    return dataSource;
    }

    public static Connection getConnection() throws SQLException{
    return dataSource.getConnection();
    }

    // 获取连接对象
    public static Connection getCurrentConnection() throws SQLException {

    Connection con = tl.get();
    if (con == null) {
    con = dataSource.getConnection();
    tl.set(con);
    }
    return con;
    }

    // 开启事务
    public static void startTransaction() throws SQLException {
    Connection con = getCurrentConnection();
    if (con != null) {
    con.setAutoCommit(false);
    }
    }

    // 事务回滚
    public static void rollback() throws SQLException {
    Connection con = getCurrentConnection();
    if (con != null) {
    con.rollback();
    }
    }

    // 提交并且 关闭资源及从ThreadLocall中释放
    public static void commitAndRelease() throws SQLException {
    Connection con = getCurrentConnection();
    if (con != null) {
    con.commit(); // 事务提交
    con.close();// 关闭资源
    tl.remove();// 从线程绑定中移除
    }
    }

    // 关闭资源方法
    public static void closeConnection() throws SQLException {
    Connection con = getCurrentConnection();
    if (con != null) {
    con.close();
    }
    }

    public static void closeStatement(Statement st) throws SQLException {
    if (st != null) {
    st.close();
    }
    }

    public static void closeResultSet(ResultSet rs) throws SQLException {
    if (rs != null) {
    rs.close();
    }
    }

    }

    映入连接:

    <?xml version="1.0" encoding="UTF-8"?>
    <c3p0-config>
        <default-config>
            <property name="user">root</property>
            <property name="password">root</property>
            <property name="driverClass">com.mysql.jdbc.Driver</property>
            <property name="jdbcUrl">jdbc:mysql:///xiaomi</property>
        </default-config>
    </c3p0-config>

  • 相关阅读:
    Java类对象转json字符串,servlet或js的json字符串转json对象或数组
    大三下每周总结--第一周
    阅读架构漫谈九篇博客有感-1500字
    大三上寒假15天--第15天
    大三上寒假15天--第14天
    大三上寒假15天--第13天
    jenkins+appium android app自动化测试
    windows jenkins 卸载
    jenkins运行Python
    pytest+jenkins安装+allure导出报告
  • 原文地址:https://www.cnblogs.com/yanglin666/p/10514362.html
Copyright © 2011-2022 走看看