BoneCP语句句柄无法施展JDBC

问题描述:

我试图建立一个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(); 
      } 
     } 
    } 

这很简单:如果你使用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