Sqlite JDBC driver not supporting RETURN_GENERATED_KEYS

前端 未结 2 2031
南笙
南笙 2021-01-05 18:51

I am using Xerial latest jdbc driver for sqlite (version 3.7.2) It does not seem to have support for Statement RETURN_GENERATED_KEYS. I keep getting \"not implemented by SQL

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-05 19:38

    If upgrading/replacing the JDBC driver is not an option (the SQLiteJDBC seem to support it), then you really need to fire a SELECT last_insert_rowid() query to obtain the generated key. To avoid race conditions with concurrent inserts, fire it in a transaction.

    connection = database.getConnection();
    connection.setAutoCommit(false); // Starts transaction.
    preparedStatement = connection.prepareStatement(INSERT_SQL);
    preparedStatement.setSomething(something);
    // ...
    preparedStatement.executeUpdate();
    statement = connection.createStatement();
    generatedKeys = statement.executeQuery("SELECT last_insert_rowid()");
    if (generatedKeys.next()) {
        generatedKey = generatedKeys.getLong(1);
    }
    connection.commit(); // Commits transaction.
    

提交回复
热议问题