本文介绍了插入原始查询后,SQLite生成的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题是在此处之前提出的,我回答了其中一个,但它不起作用,我生成的ID为0.该问题基于最后给出的答案.

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.

可接受的答案使用long id = db.insert(...);由android提供,但我想知道为什么我们不能从原始查询中获取生成的ID?

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
        }
    }
}


编辑

我意识到,问题出在这条语句上,即使moveToNext为true,它也总是返回0,科特林的任何专家都可以建议吗?

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?

推荐答案

rawQuery()本身不会执行查询,除非您移动结果Cursor.

rawQuery() by itself does not execute the query until you move the resulting Cursor.

对于不返回结果的SQL,请使用execSQL(),例如INSERT.

Use execSQL() instead for SQL that does not return a result, such as INSERT.

这篇关于插入原始查询后,SQLite生成的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 20:36