java - BoneCP 语句句柄无法转换为 JDBC

标签 java sql jdbc bonecp

我正在尝试设置 BonusCP 连接,但收到以下错误消息:

线程“main”中的异常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 接口(interface)不足以满足你?

关于java - BoneCP 语句句柄无法转换为 JDBC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11377295/

相关文章:

mysql - "error in your SQL syntax check the manual corresponds"一页消息

mysql - 如何对sql中多列的相似值进行选择

Mysql统计所有包含数字1、2、3或4的列

java - 为防止内存泄漏,已强制注销 JDBC 驱动程序

java - 与 argThat 匹配仅适用于具有单个参数的方法吗?

java - Play 框架中正确转义的指南

java - 使用递归反转字符串

java - 将行添加到具有唯一列 : Get existing ID values plus newly-created ones 的表

java - 如何查找结果集的磁盘使用情况?

java - 我可以编写一个用于登录目的的java应用程序吗?