【问题标题】:Inserting multiple entries into SQLite database android将多个条目插入SQLite数据库android
【发布时间】:2013-04-17 00:49:39
【问题描述】:

我在将多个条目插入 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) 让它工作,但替换了插入以加快速度。

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

【问题讨论】:

  • 你的问题是什么?
  • 光标什么也不返回。
  • 你能发布你的插入代码吗?您是使用 sql 脚本还是插入内容值?

标签: android android-sqlite


【解决方案1】:

回答我自己的问题。

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

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

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

【讨论】:

  • 想过提出这个建议,但没想到会是这样的性能提升器。通常您可以将executeBatch() 与 JDBC 一起使用,这也是一个非常好的功能 (viralpatel.net/blogs/batch-insert-in-java-jdbc)。
  • 谢谢,这个答案真的帮助了我!值得注意的是 Trinimon 的可编译语法示例无效,正确的示例应该是:String sql = "INSERT INTO coordiantes VALUES(?, ?, ?, ?)"
【解决方案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();
}

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

【讨论】:

  • 糟糕,复制/粘贴错误。我取出了一些字段来简化问题。我更新了问题。我将尝试实现这个插入方法,看看它是否有效。谢谢。
  • 好的,我从这里删除了我的提示,因为它不再有效。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-21
  • 2014-04-21
相关资源
最近更新 更多