Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

android - 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 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...