JDBC知識學習——事務、dbcp連接池及c3p0連接池

一:事務

①事務:一組邏輯操作單元,使數據從一種狀態變換到另一種狀態並保證數據的一致性。原子性、一致性、隔離性、持久性。
②隔離級別:讀未提交數據READ UNCOMMITTED、讀已提交數據READ COMMITTED、可重複讀REPEATABLE READ、串行化SERIALIZABLE。
③在當前的cmd窗口中查看MySQL隔離級別:select @@tx_isolation
設置當前MySQL連接的隔離級別:set transaction isolation level read committed
設置數據庫系統的全局 隔離級別:set global transaction isolation level committed
代碼示例:

public class BussinessTest {
    @Test
    public  void TestTransaction(){
        Connection connection=null;
        try {
            connection=JDBCTools.getConnection();
            //事務開始,取消默認提交
            connection.setAutoCommit(false);
            String sql1="";
            update(connection,sql1);
            String sql2="";
            update(connection,sql2);
            //提交事務
            connection.commit();
        }catch (Exception e){
            e.printStackTrace();
            try {
                //回滾事務
                connection.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }finally {
JDBCTools.releaseSource(null,null,connection);
        }
    }
    @Test
    public void testBatch(){
        /*
        * 批量處理sql提高執行速度和效率
        * */
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        String sql=null;
        try {
            connection=JDBCTools.getConnection();
            //開始事務
            connection.setAutoCommit(false);
             sql="insert into user values(?,?)";
            preparedStatement=connection.prepareStatement(sql);
            long beginTime=System.currentTimeMillis();
            for (int i = 0; i < 100000; i++) {
                preparedStatement.setInt(1,i+1);
                preparedStatement.setString(2,"name_"+i);
                //儲蓄要執行的sql
                preparedStatement.addBatch();
                if((i+1)%200 ==0){
                    //積累到200條是統一執行
                    preparedStatement.executeBatch();
                    //執行完成後清空
                    preparedStatement.clearBatch();
                }
            }
            long endTime=System.currentTimeMillis();
            System.out.println(endTime-beginTime);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBCTools.releaseSource(null,preparedStatement,connection);
        }
    }
/**
*@ClassName BussinessTest
*@Description 執行sql的方法
*@Param [connection, sql, args]
*@Return void
*@Date 2020/2/17 15:52
*@Author Roy
*/
    public void update(Connection connection,String sql,Object ... args){
        PreparedStatement preparedStatement =null;
        try {
            preparedStatement=connection.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                preparedStatement.setObject(i+1,args[i]);
            }
            preparedStatement.executeUpdate();
        }catch (Exception e){
        e.printStackTrace();
        }finally {
        JDBCTools.releaseSource(null,preparedStatement,null);
        }
    }
}

二:dbcp連接池使用

注意: 加入jar包commons-dbcp.jar且依賴於commons-pool-1.5.6.jar包
代碼使用示例:

public class PoolTest {
    /*
    * dbcp factory測試
    * */
    @Test
    public void testDbcpFactory() throws Exception {
        Properties properties=new Properties();
        //文件輸入流
        InputStream in=PoolTest.class.getClassLoader().getResourceAsStream("dbcp.properties");
        properties.load(in);
        //創建連接屬性
        DataSource dataSource=BasicDataSourceFactory.createDataSource(properties);
        //獲取連接
        Connection connection=dataSource.getConnection();
        System.out.println(connection);
    }

    /*
    *使用DBCP數據庫連接池
    * 加入jar包commons-dbcp.jar且依賴於commons-pool-1.5.6.jar包
     *  */
    @Test
    public void testDBCP(){
        BasicDataSource dataSource=null;
        //創建實例
        dataSource=new BasicDataSource();
        //指定連接屬性
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        dataSource.setUrl("jdbc:mysql://localhost:3306/test");
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        //指定數據庫連接池中初始化連接的數量
        dataSource.setInitialSize(8);
        //指定最大的連接數:指同時可以向數據庫申請的連接數
        dataSource.setMaxActive(40);
        //指定最小連接:指連接池保存的最少的空閒連接的數量
        dataSource.setMinIdle(3);
        //最長的等待時間:等待數據庫分配連接的最長時間毫秒
        dataSource.setMaxWait(2000);

        //獲取連接
        try {
            Connection connection=dataSource.getConnection();
            System.out.println(connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

三:c3p0連接池使用

使用c3p0數據源
①:導入c3p0-0.9.2.1.jar文件並創建c3p0-config.xml配置文件
②:創建c3p0-config.xml配置文件在module顯得src下創建file命名爲:c3p0-config.xml。
並在此文件中輸入以下配置:

<c3p0-config>
    <named-config name="hello">
        <!--連接數據庫的基本屬性-->
        <property name="user">root</property>
        <property name="password">123456</property>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/test</property>
        <!--若數據庫中連接數不足時,一次向數據庫服務器申請多少個連接-->
        <property name="acquireIncrement">5</property>
        <!--初始化連接數據庫連接池的數量-->
        <property name="initialPoolSize">10</property>
        <!--初始化連接池中的最小數據庫連接數-->
        <property name="minPoolSize">5</property>
        <!--初始化連接池中的最大數據庫連接數-->
        <property name="maxPoolSize">10</property>
        <!--數據庫連接池可以維護的Statement的個數-->
        <property name="maxStatement">0</property>
        <!--每個連接可以同時使用Statement對象的個數-->
        <property name="maxStatementsPerConnection">5</property>
    </named-config>
</c3p0-config>

現在即可以使用代碼測試:

public class c3p0Test {
    //使用配置文件連接
    @Test
    public void testC3P0Config(){
        DataSource dataSource=
                new ComboPooledDataSource("hello");
        Connection connection= null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            if(connection!=null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println(connection);
    }
    //使用c3p0連接
    @Test
    public void testC3P0() throws Exception {
        ComboPooledDataSource cpds=new ComboPooledDataSource();
        cpds.setUser("root");
        cpds.setPassword("123456");
        cpds.setJdbcUrl("jdbc:mysql://localhost:3306/test");
        cpds.setDriverClass("com.mysql.jdbc.Driver");
        Connection connection=cpds.getConnection();
        System.out.println(connection);
        connection.close();
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章