【问题标题】:prepareStatement doesn't work with sqliteprepareStatement 不适用于 sqlite
【发布时间】:2014-04-09 14:03:38
【问题描述】:

我尝试使用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 或者我的驱动程序有问题(例如由于过时)?

【问题讨论】:

    标签: java sqlite jdbc prepared-statement


    【解决方案1】:

    你不需要将sql 变量传递给executeUpdate 方法,因为你已经在prepareStatement 语句上配置了它,所以试试吧:

    stmt.executeUpdate();
    

    【讨论】:

    • 哦,谢谢。我刚试了一下,它奏效了。但它提供了多么误导的错误信息!
    【解决方案2】:

    PreparedStatement 有点双重生活:它extends Statement,因此继承了该类的方法——尽管其中一些对PreparedStatement 没有多大意义。

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

    【讨论】:

    • 另见几年前的this thread。看起来 sqlite 的人都知道它,但这对他们来说不是一个高优先级的问题。
    猜你喜欢
    • 2018-03-16
    • 2012-04-12
    • 1970-01-01
    • 2011-12-24
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    • 2016-11-11
    • 1970-01-01
    相关资源
    最近更新 更多