每个查询的java c3po语句

时间:2013-09-17 14:42:04

标签: java jdbc c3p0

我是JDBC的初学者,在我的研究中,我发现对C3PO的最佳评论,因为我已经尝试过BoneCP,但却发现它没有关闭连接。

我需要一个连接池,也许还有一个语句池,用于多线程软实时软件(交易系统)

这是“SELECT”的一个例子:

  1. 好吗?
  2. 我是否需要getConn()然后创建语句并关闭每个查询?
  3. 任何一般性意见或建议?

            Connection conn = null;
    ResultSet rs = null;
    Statement st = null;
    String query = null;
    try {
    
        query = " SELECT id " +
                  " FROM " + DBTables.PandaSources;
    
        //rs = DB.ConnPool.invoke(conn, query, rs);
        st = DB.ConnPool.getSt();
        rs = st.executeQuery(query);
    
        if (rs != null) {
            while (rs.next()) {
                .....
                                    ......
            }
        }
    } 
    catch (Exception e) { 
        e.printStackTrace(); 
        Util.logException(e);
    }
    finally {
        if (rs != null) try { rs.close(); } catch (SQLException e) { e.printStackTrace(); Util.logException(e); }
        if (st != null) try { st.close(); } catch (SQLException e) { e.printStackTrace(); Util.logException(e); }
        if (conn != null) try { conn.close(); } catch (SQLException e) { e.printStackTrace(); Util.logException(e); }
    }
    
    query = null;
    st = null;
    rs = null;
    conn = null;
    }
    
      public static synchronized Statement getSt() throws SQLException {
    return getConn().createStatement();
      }
    
     public static synchronized Connection getConn() throws SQLException {
       if (connectionPoolDatasource == null) {
          initPool();
       }
       return connectionPoolDatasource.getConnection();
    

    }

     public static synchronized void initPool() throws SQLException {
    
    DBLocation loc = null;
    try {
    
        loc = GTMain.DBConn.get(Util.DB_GURUSTRADE);
    
        // C3PO
        connectionPoolDatasource = new ComboPooledDataSource();
        connectionPoolDatasource.setDriverClass(loc.driver);
        connectionPoolDatasource.setJdbcUrl(loc.url);
        connectionPoolDatasource.setUser(loc.user);
        connectionPoolDatasource.setPassword(loc.password);
    
        // properties
        connectionPoolDatasource.setAcquireIncrement(5);
        connectionPoolDatasource.setMaxIdleTime(3600);
        connectionPoolDatasource.setMaxIdleTimeExcessConnections(300);
        connectionPoolDatasource.setMaxPoolSize(100);
        connectionPoolDatasource.setMinPoolSize(20);
        connectionPoolDatasource.setNumHelperThreads(6);
        connectionPoolDatasource.setUnreturnedConnectionTimeout(3600);
    
    }
    catch (Exception e) {
        e.printStackTrace(); 
    }
    

    }

0 个答案:

没有答案