sqlite java.sql.SQLException:无法对PreparedStatement调用方法

mdfafbf1  于 2023-08-06  发布在  SQLite
关注(0)|答案(1)|浏览(157)

我想使用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;
}


它与本机查询语句执行一起工作,因此它不是与连接相关的问题。你知道吗?

a0zr77ik

a0zr77ik1#

问题是您的一些方法在PreparedStatement上调用executeQuery(String)executeUpdate(String),而这是API不允许的。如果发生这种情况,则需要一致性实现来抛出SQLException
Statement.executeQuery(String)(强调我的)所述:

投掷次数:

SQLException-如果发生数据库访问错误,则在已关闭的Statement上调用此方法,给定的SQL语句生成除单个ResultSet对象之外的任何对象,该方法在PreparedStatementCallableStatement上调用
对于Statement上的其他execute方法也有相同的记录。
您需要使用executeQuery()executeUpdate(),或者需要使用Statement而不是PreparedStatement

相关问题