prepareStatement不能与sqlite一起使用。

6

我尝试使用prepareStatement查询sqlite,但遇到了异常:

java.sql.SQLException: not supported by PreparedStatment
    at org.sqlite.PrepStmt.unused(PrepStmt.java:328)
    at org.sqlite.PrepStmt.executeUpdate(PrepStmt.java:314)

我正在使用Eclipse开发我的程序,所以当我点击 at org.sqlite.PrepStmt.unused(PrepStmt.java:328) 时,它会将我重定向到 PrepStmt.class,在其中我找到了以下内容:

@Override
public int executeUpdate(String sql) throws SQLException {
    throw unused();
}
private SQLException unused() {
    return new SQLException("not supported by PreparedStatment");
}

这是我的代码:
public static void deleteOp(String word) throws Exception {
    Connection c = null;
    PreparedStatement stmt = null;
    try {
      Class.forName("org.sqlite.JDBC");
      c = DriverManager.getConnection(connectionString);
      c.setAutoCommit(false);
      System.out.println("Opened database successfully");

      String sql = "DELETE from " + tableName + " where WORD = ? ;";
      System.out.println(sql);
      stmt = c.prepareStatement(sql);
      stmt.clearParameters();
      stmt.setString(1, word);
      stmt.executeUpdate(sql);
      c.commit();

      stmt.close();
      c.close();
    } catch ( Exception e ) {
        throw e;
    }
    System.out.println("Operation done successfully");
}

我想知道我的代码有问题还是Sqlite根本不支持prepareStatement,或者我的驱动程序存在问题(例如由于过时)?

2个回答

7

您无需将sql变量传递给executeUpdate方法,因为您已经在prepareStatement语句中进行了配置,所以只需尝试:

stmt.executeUpdate();

1
哦,谢谢。我刚试了一下,它起作用了。但是它提供的错误信息太具有误导性了! - Mohsen Kamrani

4
PreparedStatement 有一种双重身份:它扩展了Statement,因此继承了该类的方法——尽管其中一些对于PreparedStatement并不真正有意义。

在这种情况下,executeUpdate(String)来自Statement,直接运行语句,而不进行?替换。这并不是你想要的:你需要的只是executeUpdate(),这是PreparedStatement的变体。所以从某种意义上说,他们实际上没有实现Statement的变体,反倒是在帮助你!


1
请参考几年前的这个帖子。看起来SQLite的开发人员已经知道了这个问题,但对他们来说并不是一个高优先级的问题。 - yshavit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接