Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prepareStatement doesn't work with sqlite

I try to use prepareStatement to query an sqlite but I encounter an exception:

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

I'm developing my program using Eclipse, so when I click on at org.sqlite.PrepStmt.unused(PrepStmt.java:328) it redirects me to PrepStmt.class that inside it I found these:

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

This is my code :

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");
}

I want to know is something wrong in my code or Sqlite doesn't support prepareStatement at all or there is a problem with my driver (for example due to being obsolete)?

like image 401
mohsen kamrani Avatar asked Mar 06 '14 18:03

mohsen kamrani


2 Answers

You don't need to pass sql variable to executeUpdate method since you have configured it on prepareStatement sentence, so just try:

stmt.executeUpdate();
like image 137
Ernesto Campohermoso Avatar answered Nov 10 '22 12:11

Ernesto Campohermoso


PreparedStatement lives a bit of a double life: it extends Statement, and thus inherits that class' methods — even though some of them don't really make much sense for PreparedStatement.

In this case, executeUpdate(String) comes from Statement and runs a statement straight-up, without doing the ? substitutions. It's not what you want: you want just executeUpdate(), which is the PreparedStatement variant. So in some sense, they're actually doing you a favor by not implementing the Statement variant!

like image 21
yshavit Avatar answered Nov 10 '22 13:11

yshavit