sqlite - 黑莓 SQLite 批量删除最佳实践

标签 sqlite blackberry

我有一个 SQLite 数据库,我需要定期删除其中的记录。从性能角度来看,最好的方法是什么?我有一系列独特的 PK ID。我想出了两种方法:

使用准备好的语句

    int[] ids = {1,2,3,4,5}; //example only, will be built elsewhere
    Database db = null;
    try {
        db = DataConnection.getInstance(); //my class to get the connection instance
        db.beginTransaction();
        Statement st = db.createStatement("DELETE FROM myTable WHERE id = ?");
        st.prepare();
        for (int i=0;i<ids.length;i++) {
            st.bind(1, ids[i]);
            st.execute();
            st.reset();
        }
        db.commitTransaction();
    } catch (FileIOException e) {
        e.printStackTrace();
    } catch (DatabaseException e) {
        e.printStackTrace();
    }

或者使用“in”关键字

    int[] ids = {1,2,3,4,5}; //example only, will be built elsewhere
    Database db = null;
    try {
        db = DataConnection.getInstance();
        //Util.JoinArray(int[] ids,char delim, char prepend, char postpend) returns a String of the ids separated by delim with prepend at the front and postpend at the end
        Statement st = db.createStatement("DELETE FROM myTable WHERE id IN " + Util.joinArray(ids,',','(',')'));
        st.prepare();
    } catch (FileIOException e) {
        e.printStackTrace();
    } catch (DatabaseException e) {
        e.printStackTrace();
    }

最佳答案

理想的方法是两者的结合:所有 ID 的准备语句。

因此,请避免 SQL 注入(inject)并使用这样的方法(以伪代码形式):

query = "DELETE FROM myTable WHERE id IN (";
for (int i = 0; i < ids.count; i++)
    query.Append("?,");
query.DropLast(); //Remove the last comma
query.Append(")");
st = db.createStatement(query);
st.prepare();
for (int i = 0; i < ids.count; i++)
    st.bind(i+1, ids[i]);

就性能而言,这可能会更好,因为数据库将在所有删除后重新平衡索引。不过,在事务中工作并在所有单独删除后提交一次本质上是相同的。我建议的方法更加安全。

正如 SO 上经常讨论的那样,SQLite 性能因各种标准而异,即结构、行数、页面大小等。SQLite 不存在通用的“在所有情况下都更快”的方法。您的里程会有所不同。

关于sqlite - 黑莓 SQLite 批量删除最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8934181/

相关文章:

android - 在 MainActivity 中激活 SQLiteHandler

javascript - 如何配置 Sequelize ORM 以执行序列化查询

sqlite - 使用sqlite3 .import命令是否会覆盖目标表中的数据?

javascript - Blackberry Web Works 如何在每次启动应用程序时触发事件

user-interface - BlackBerry - 自定义菜单工具栏

java - VerticalFieldManager 中的黑莓字段对齐

java - Android sqlite 升级时出现重复列

Android: CheckedTextView + SQLite的ListView,用Adapter显示选中的行?

debugging - 在黑莓设备上调试的最有效方法?

java - Blackberry:加速模拟器启动