java BoneCP语句句柄不能强制转换为JDBC
我正在尝试设置boneCP连接,收到以下错误消息:
线程“main”java中出现异常。lang.ClassCastException:com。乔博克斯。博内普。无法将StatementHandle强制转换为com。mysql。jdbc。声明
连接似乎工作正常,但我在查询时被阻止了
这是我的密码:
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,您应该能够使用^{} 获得包装语句(尽管我不是100%确定)
尽管最大的问题是:为什么需要强制转换到
com.mysql.jdbc.Statement
,但是java.sql.Statement
接口对您来说还不够吗