当前位置: 代码迷 >> java >> 尽管在查询中指定了数据库所选异常,但不会发生
  详细解决方案

尽管在查询中指定了数据库所选异常,但不会发生

热度:27   发布时间:2023-07-18 09:01:32.0

我有一个查询

    SELECT * FROM dbName.dbTable

我正在使用准备好的语句执行查询。

这是HicariCP配置设置:

    hconfig.setDriverClassName("com.mysql.jdbc.Driver");
    hconfig.setJdbcUrl("jdbc:mysql://localhost/?useUnicode=true&characterEncoding=UTF8&cachePrepStmts=true&prepStmtCacheSize=250&useServerPrepStmts=true&rewriteBatchedStatements=true&continueBatchOnError=false&prepStmtCacheSqlLimit=2048");
    hconfig.setUsername("user");
    hconfig.setPassword("passwd");
    hconfig.setMaximumPoolSize(10);
    hconfig.setConnectionTimeout(60000);
    HikariDataSource hikariDataSource= new HikariDataSource(hconfig);

客户端用法:

    Client client;
    client.executePreparedQuery(
                    "SELECT * FROM dbName.dbTable",
                    null,
                    new ResultSetBinder() {
                        @Override
                        public void bind(ResultSet resultSet) throws SQLException {
                            // binding the result goes here
                        }
                    });

Client类的相关方法(executePreparedQuery):

    Connection con = hikariDataSource.getConnection();
    PreparedStatement ps = con.prepareStatement(sql);
    ResultSet rs = null;
    try {
        if (psb != null) {
            psb.bind(ps);
        }

        rs = ps.executeQuery();
        while (rs.next()) {
            if (rsb != null) {
                rsb.bind(rs);
            }
        }
    } finally {
        close(rs, ps, con);
    }

尽管要使用的数据库已在查询本身中进行了修饰,但是代码有时(并非总是如此!)会抛出java.sql.SQLException: No database selected.

HicariCP使用MySQL 5.6.22

可能是什么原因?

HicariCP Config设置:

添加=> hconfig.addDataSourceProperty(“ databaseName”,“ yourDatabaseName”);

hconfig.setDriverClassName("com.mysql.jdbc.Driver");
hconfig.setJdbcUrl("jdbc:mysql://localhost/?useUnicode=true&characterEncoding=UTF8&cachePrepStmts=true&prepStmtCacheSize=250&useServerPrepStmts=true&rewriteBatchedStatements=true&continueBatchOnError=false&prepStmtCacheSqlLimit=2048");
hconfig.setUsername("user");
hconfig.setPassword("passwd");
hconfig.setMaximumPoolSize(10);
hconfig.setConnectionTimeout(60000);
hconfig.addDataSourceProperty("databaseName", "yourDatabaseName");
HikariDataSource hikariDataSource= new HikariDataSource(hconfig);

客户端用法:

更改为=> “ SELECT * FROM dbTable”

    Client client;
    client.executePreparedQuery(
                    "SELECT * FROM dbTable",
                    null,
                    new ResultSetBinder() {
                        @Override
                        public void bind(ResultSet resultSet) throws SQLException {
                            // binding the result goes here
                        }
                    });

希望它会有所帮助。

  相关解决方案