简体   繁体   English

Android SQLite查询插入后不返回数据

[英]Android SQLite query not returning data after insert

I'm attempting to insert data to an SQLite database table and then immediately return the result from a select in the same call, but no data is returned. 我试图将数据插入到SQLite数据库表中,然后在同一调用中立即从select中返回结果,但是没有返回数据。

Here is the SQL statement: 这是SQL语句:

INSERT INTO Items (Name, DefaultExpirationIntervalId) VALUES ('Item', -1);
SELECT ItemId as '_id', Name, DefaultExpirationIntervalId FROM Items WHERE Name = 'Item';

Here is the code making the SQL call: 这是进行SQL调用的代码:

        Boolean isReadOnly = getSQLiteDatabase().isReadOnly();

        // Make sure we can add data to the database
        if (!isReadOnly)
        {
            // Add the item to the database and then use the result to create a new item
            Cursor cursor = getSQLiteDatabase().rawQuery(query, null);

            if (null != cursor)
            {
                cursor.moveToFirst();

                if (!cursor.isAfterLast())
                    item = new Item(cursor);
            }
        }

The rawQuery call returns a cursor (not null), but it is empty. rawQuery调用返回一个游标(不为null),但它为空。

I verified through ADB that the record was inserted. 我通过亚行验证是否已插入记录。 I've even run this exact query through sqlite3 via the ADB shell and the item was inserted and returned as expected. 我什至通过ADB Shell在sqlite3中运行了这个确切的查询,并且该项目已按预期插入并返回。 I have also tried removing the select and retrieving the item in another rawQuery call and that didn't work either. 我也尝试过删除选择并在另一个rawQuery调用中检索该项目,但这也不起作用。

Does anybody have any idea what might be happening? 有人知道会发生什么吗? I am running this code through a unit test that creates and and destroys the database during every test run. 我正在通过单元测试运行此代码,该单元测试在每次测试运行期间都会创建和销毁数据库。

rawQuery is used ONLY for SELECT statements. rawQuery仅用于SELECT语句。
For INSERT, DELETE and UPDATE , you have to use execSQL instead 对于INSERT,DELETE和UPDATE ,必须改用execSQL

So, first you must make an INSERT by using execSQL AND THEN use rawQuery for your SELECT. 因此,首先,您必须使用execSQL进行INSERT,然后对您的SELECT使用rawQuery。

In case you're asking why... 万一你问为什么...
a SELECT is a QUERY, while INSERT, DELETE and UPDATE are COMMANDS. SELECT是一个查询,而INSERT,DELETE和UPDATE是命令。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM