【问题标题】:compileStatement or db.insert in androidandroid 中的 compileStatement 或 db.insert
【发布时间】:2014-04-08 21:19:06
【问题描述】:

我想多次向表中插入记录,我可以选择使用 compileStatement 或使用 db.insert,如下所示。

String TABLENAME = "table"; //fields in table: id, name
SQLiteStatement statement = db.compileStatement("INSERT INTO "+TABLENAME+" VALUES(?,?);");  
statement.bindLong(1,666);  
statement.bindString(2,"john");
statement.executeInsert();

String TABLENAME = "table";
ContentValues values = new ContentValues();
values.put("id", 666);
values.put("name", "john");
db.insert(TABLENAME, null, values);

哪一个应该是最优的?

编辑:- 我正在运行的应用程序是单线程的。

【问题讨论】:

  • 如果您想要更好的性能,请使用事务。
  • 我正在使用这个和类似的代码段来插入多个表,如果任何插入失败,我打算回滚所有表,所以我将它们包含在 beginTransaction 和 endTransaction 和 setTransactionSuccessful if all插入成功。你能详细说明我应该如何改变这种方法
  • 到目前为止,您的方法对我来说似乎是正确的。

标签: android sqlite query-optimization android-sqlite


【解决方案1】:

insert() 在每次调用时编译 SQL,而 compileStatement() 方法只编译一次 SQL。当多次使用具有不同绑定参数的同一 SQL 时,compileStatement() 方法的工作量更少,速度更快。

此外,考虑将插入包装在事务中以减少等待 I/O 所花费的时间。

【讨论】:

  • 我正在插入多个表,插入到我在事务中包装的所有表中,我打算将它们全部失败,以防任何一个插入失败。您能否详细说明应如何更改包装交易的方法
  • 1.开始交易。 2. 开始一个try 块。 3. 在try 中进行插入 4. 在try 中设置事务成功。 5.在tryfinally区块中结束交易。
  • 我目前使用:db.beginTransaction(); try { ` //插入A表` ` //插入B表` ` //插入C表` ` //插入table D` ` db.setTransactionSuccessful();` } catch(Exception e) { //捕获异常` } finally{ ` db.endTransaction();` }
【解决方案2】:

理论上,编译语句更好,但在 Android 设备上,您不太可能处理如此多的记录,以至于差异很重要。 (如果你想确定,你必须自己衡量。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-22
    • 2014-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多