3

我在将多个条目插入 Android SQLite 数据库时遇到问题。我用 db.execQuery() 像这样插入:

String insertString = "INSERT INTO coordinates 
    SELECT 0 AS _id, 5 AS associated_route_id, 38.88945 AS latidude, -77.034821 AS longitude 
    UNION SELECT 1, 5, 38.889671, -77.034912 
    UNION SELECT 2, 5, 38.890041, -77.035316"
database.execSQL(insertString);

我稍后使用相同的数据库进行拉取,如下所示:

String[] columns = new String[] { "latitude", "longitude" };
Cursor cursor = db.query("coordinates", columns,
                "associated_route_id=5", null, null, null,
                null);

cursor.moveToFirst();
if (cursor.getCount() == 0)
// No rows in cursor

我使用 db.insert(table, null, contentValues) 让它工作,但替换了插入以使事情更快。

问题是光标是空的,这使得插入似乎不起作用。为什么它不起作用?

4

2 回答 2

10

回答我自己的问题。

我使用了不同的方法来插入条目。我使用 Trinimon 的建议来使用 db.compileStatement,但增加插入时间最多的是添加:

db.startTransaction();
//insert lots of stuff...
database.setTransactionSuccessful();
database.endTransaction();

插入 500 个条目的时间从 45 秒减少到 300 毫秒。

于 2013-04-23T19:41:07.940 回答
2

插入记录最快的方法是使用带有绑定变量的预处理语句,因为语句不需要一直编译,例如:

String sql = "INSERT INTO coordinates (?, ?, ?, ?)";
SQLiteStatement statement = db.compileStatement(sql);

// loop through records or arrays and assign values
for (...) { 
    long id = ...
    long associated_route_id = ...
    double latidude = ...
    double longitude = ...

    statement.bindLong  (1, id);
    statement.bindLong  (2, associated_route_id);
    statement.bindDouble(3, latidude);
    statement.bindDouble(4, longitude);

    statement .execute();
}

希望这会有所帮助......干杯!

于 2013-04-23T17:41:48.950 回答