尽管在查询中指定了异常但未发生数据库选择异常

时间:2015-07-30 14:35:19

标签: java mysql jdbc

我有一个像

这样的查询
    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.

MySQL 5.6.22HicariCP一起使用。

可能是什么原因?

1 个答案:

答案 0 :(得分:0)

HicariCP配置设置:

add => 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);

客户端使用情况:

chnage to => “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
                        }
                    });

希望它会有所帮助。