如果升级/更换JDBC驱动程序不是一个选项(SQLiteJDBC似乎支持它),那么您确实需要触发SELECT last_insert_rowid()
查询来获取生成的密钥。为了避免并发插入竞争条件,在事务中激发它。
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.
如果驱动程序不支持它,您需要一个新的驱动程序,另一个数据库或自己编写SELECT。无法保证您提供的示例查询将适用于多位并发用户。 – duffymo 2010-11-28 18:41:26