-1

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 accepted answer used long id = db.insert(...); provided by the android but I'm wondering why can't we get the generated id from raw queries?

fun save(): Long {
    val sql = "INSERT INTO user(first, last) VALUES(?, ?)"
    connection.writableDatabase.rawQuery(sql, arrayOf("John", "Doe")).use {
        connection.writableDatabase.rawQuery("SELECT last_insert_rowid()", null).use {
            return if (it.moveToNext()) it.getLong(0) else 0
        }
    }
}

EDIT

I realized something, the issue is with this statement, this always returns 0 even if moveToNext is true, anyone expert in kotlin can advise?

return if (it.moveToNext()) it.getLong(0) else 0

I was supposed to use the ternary operator but whats the problem in here to begin with?

AppDeveloper
  • 1,816
  • 7
  • 24
  • 49
  • The recommended method to insert new rows is `insert()` which returns the rowid of the row that you insert. If you don't get the correct result for the rowid then the problem is with your code and this is what you should attempt to correct instead of trying to figure out what is wrong with undocumented features of `rawQuery()`. – forpas Dec 04 '20 at 10:02

2 Answers2

0

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.

laalto
  • 150,114
  • 66
  • 286
  • 303
0

Based on laalto's answer to get a confirmation.

fun save(): 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 ->
        return if (cursor.moveToNext()) cursor.getLong(0) else null
    }
}

fun update(): 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 ->
        return if (cursor.moveToFirst()) cursor.getInt(0) else null
    }
}
AppDeveloper
  • 1,816
  • 7
  • 24
  • 49