Sqlite Generated Id After Insert Raw Query
This question was asked in here before and I took one of the answers but its not working, I'm getting generated id as 0. This question is based on the last given answer. The accept
Solution 1:
rawQuery()
by itself does not execute the query until you move the resulting Cursor
.
Use execSQL()
instead for SQL that does not return a result, such as INSERT
.
Solution 2:
Based on laalto's answer to get a confirmation.
funsave(): Long? {
val sql = "INSERT INTO user(first, last) VALUES(?, ?)"
connection.writableDatabase.execSQL(sql, arrayOf("John", "Doe"))
connection.readableDatabase.rawQuery("SELECT last_insert_rowid()", null).use { cursor ->
returnif (cursor.moveToNext()) cursor.getLong(0) elsenull
}
}
funupdate(): Int? {
val sql = "UPDATE user SET first = ?, last = ? WHERE id = ?"
connection.writableDatabase.execSQL(sql, arrayOf("Jane", "Doe", "1"))
connection.readableDatabase.rawQuery("SELECT changes()", null).use { cursor ->
returnif (cursor.moveToFirst()) cursor.getInt(0) elsenull
}
}
Post a Comment for "Sqlite Generated Id After Insert Raw Query"