我想使用HikariCP使用SQLite连接到SQLite数据库。但是当我尝试运行查询时得到一个错误。
Exception in thread "main" java.lang.RuntimeException: java.sql.SQLException: method cannot be called on a PreparedStatement
at StatementUtility.wrapException(StatementUtility.java:110)
at StatementUtility.executeUpdate(StatementUtility.java:101)
at Database.createTables(Database.java:27)
at Database.<init>(Database.java:23)
at Main.main(Main.java:10)
字符串
Hikari连接设置:
public Client () {
HikariConfig config = new HikariConfig();
config.setPoolName("AuthMeSQLitePool");
config.setDriverClassName("org.sqlite.JDBC");
config.setConnectionTestQuery("SELECT 1");
config.setJdbcUrl("jdbc:sqlite:I:/data.db");
config.setMaxLifetime(60000);
config.setIdleTimeout(45000);
config.setMaximumPoolSize(50);
}
型
网址:StatementUtility.java
public <R> R executeQuery(String sql, ThrowingConsumer<PreparedStatement> cfg, ThrowingFunction<ResultSet, R, SQLException> op) {
return wrapException(sql, s -> {
cfg.accept(s);
return op.apply(s.executeQuery());
});
}
public int executeUpdate(String sql, ThrowingConsumer<PreparedStatement> cfg) {
return wrapException(sql, s -> {
cfg.accept(s);
return s.executeUpdate();
});
}
public <R> R executeQuery(String sql, ThrowingFunction<ResultSet, R, SQLException> op) {
return wrapException(sql, s -> op.apply(s.executeQuery(sql)));
}
public int executeUpdate(String sql) {
return wrapException(sql, s -> s.executeUpdate(sql));
}
private <T> T wrapException(String sql, @NotNull ThrowingFunction<PreparedStatement, T, SQLException> operation) {
try(Connection connection = getConnection()){
try (PreparedStatement statement = connection.prepareStatement(sql)) {
return operation.apply(statement);
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@FunctionalInterface
public interface ThrowingConsumer<T> extends Consumer<T> {
@Override
default void accept(final T elem) {
try {
acceptThrows(elem);
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
void acceptThrows(T elem) throws Exception;
}
@FunctionalInterface
public interface ThrowingFunction<T, R, E extends Exception> {
R apply(T input) throws E;
}
型
它与本机查询语句执行一起工作,因此它不是与连接相关的问题。你知道吗?
1条答案
按热度按时间a0zr77ik1#
问题是您的一些方法在
PreparedStatement
上调用executeQuery(String)
或executeUpdate(String)
,而这是API不允许的。如果发生这种情况,则需要一致性实现来抛出SQLException
。如
Statement.executeQuery(String)
(强调我的)所述:投掷次数:
SQLException
-如果发生数据库访问错误,则在已关闭的Statement
上调用此方法,给定的SQL语句生成除单个ResultSet
对象之外的任何对象,该方法在PreparedStatement
或CallableStatement
上调用对于
Statement
上的其他execute
方法也有相同的记录。您需要使用
executeQuery()
或executeUpdate()
,或者需要使用Statement
而不是PreparedStatement
。