使用MySQL連接池


手動配置連接池:

/**
     * 手動設置連接池
     */
    public void demo1(){

        // 獲得連接:
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try{
            // 創建連接池:
            ComboPooledDataSource dataSource = new ComboPooledDataSource();
            // 設置連接池的參數:
            dataSource.setDriverClass("com.mysql.jdbc.Driver");
            dataSource.setJdbcUrl("jdbc:mysql:///jdbctest");
            dataSource.setUser("root");
            dataSource.setPassword("abc");
            dataSource.setMaxPoolSize(20);
            dataSource.setInitialPoolSize(3);
            
            // 獲得連接:
            conn = dataSource.getConnection();
            // 編寫Sql:
            String sql = "select * from user";
            // 預編譯SQL:
            pstmt = conn.prepareStatement(sql);
            // 設置參數
            // 執行SQL:
            rs = pstmt.executeQuery();
            while(rs.next()){
                System.out.println(rs.getInt("uid")+"   "+rs.getString("username")+"   "+rs.getString("password")+"   "+rs.getString("name"));
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            JDBCUtils.release(rs, pstmt, conn);
        }
    }

使用配置文件配置連接池:

配置文件xml如下:

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>

  <default-config>
    <property name="driverClass">com.mysql.jdbc.Driver</property>
    <property name="jdbcUrl">jdbc:mysql:///jdbctest</property>
    <property name="user">root</property>
    <property name="password">abc</property>
    <property name="initialPoolSize">5</property>
    <property name="maxPoolSize">20</property>
  </default-config>
  
</c3p0-config>

代碼如下:

/**
     * 使用配置文件的方式
     */
    public void demo2(){
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try{
            /*// 獲得連接:
            ComboPooledDataSource dataSource = new ComboPooledDataSource();*/
            // 獲得連接:
            // conn = dataSource.getConnection();
            conn = JDBCUtils2.getConnection();
            // 編寫Sql:
            String sql = "select * from user";
            // 預編譯SQL:
            pstmt = conn.prepareStatement(sql);
            // 設置參數
            // 執行SQL:
            rs = pstmt.executeQuery();
            while(rs.next()){
                System.out.println(rs.getInt("uid")+"   "+rs.getString("username")+"   "+rs.getString("password")+"   "+rs.getString("name"));
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            JDBCUtils2.release(rs, pstmt, conn);
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM