2012-07-07 108 views
0

我試圖建立一個boneCP連接,我收到以下錯誤消息:BoneCP語句句柄無法施展JDBC

異常在線程「主要」 java.lang.ClassCastException:com.jolbox.bonecp.StatementHandle不能轉換爲com.mysql.jdbc.Statement

連接似乎工作正常,但我停止了查詢。

這裏是我的代碼:

 BoneCP connectionPool = null; 
    Connection connection = null; 

    try { 
     // load the database driver (make sure this is in your classpath!) 
     Class.forName("com.mysql.jdbc.Driver"); 
    } catch (Exception e) { 
     e.printStackTrace(); 
     return; 
    } 

    try { 
     // setup the connection pool 
     BoneCPConfig config = new BoneCPConfig(); 
     config.setJdbcUrl("jdbc:mysql://192.126.0.0:3306/"); // jdbc url specific to your database, eg jdbc:mysql://127.0.0.1/yourdb 
     config.setUsername("root"); 
     config.setPassword(""); 
     config.setMinConnectionsPerPartition(5); 
     config.setMaxConnectionsPerPartition(10); 
     config.setPartitionCount(1); 
     connectionPool = new BoneCP(config); // setup the connection pool 

     connection = connectionPool.getConnection(); // fetch a connection 

     if (connection != null){ 
      System.out.println("Connection successful!"); 
      Statement stmt = (Statement) connection.createStatement(); 
      ResultSet rs = stmt.executeQuery("SELECT 1 FROM table"); // do something with the connection. 
      while(rs.next()){ 
       System.out.println(rs.getString(1)); // should print out "1"' 
      } 
     } 
     connectionPool.shutdown(); // shutdown connection pool. 
    } catch (SQLException e) { 
     e.printStackTrace(); 
    } finally { 
     if (connection != null) { 
      try { 
       connection.close(); 
      } catch (SQLException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 

回答

1

這很簡單:如果你使用BoneCP,你不必到底層驅動的對象的直接訪問。這通常適用於連接池,因爲它們通常會使用代理來處理資源管理(例如,當連接返回到池時關閉語句,結果集等)。這特別適用於語句,因爲連接池可以(並且通常)也提供語句緩存。

特別是對於BoneCP,你應該可以使用StatementHandle.getInternalStatement()(儘管我對此並不是100%確定)可以得到封裝的語句。

雖然最大的問題是:爲什麼你需要投到com.mysql.jdbc.Statement,是不是java.sql.Statement界面足以滿足你?

+0

我不知道如何回答你的問題?我應該如何構建我的代碼來做一個簡單的查詢? – scriptdiddy 2012-07-07 19:39:20

+0

您通常應該只與JDBC接口通話,而不能與特定驅動程序的類通信。在你問題的代碼中,沒有什麼不能通過簡單地使用'java.sql.Statement'來完成。因此,用'java.sql.Statement'替換(我期望的)'com.mysql.jdbc.Statement'的導入(這也將消除您應用的轉換的需要)。 – 2012-07-07 19:44:36

+0

謝謝你的幫助^ !!你知道我怎麼可以將連接傳遞給動作監聽器(線程),以便我可以每次迭代查詢數據庫? – scriptdiddy 2012-07-07 19:53:58