【问题标题】:How to bind values to SQLiteStatement for insert query?如何将值绑定到 SQLiteStatement 以进行插入查询?
【发布时间】:2017-01-29 13:32:30
【问题描述】:

使用SQLiteStatement的插入代码通常是这样的,

String sql = "INSERT INTO table_name (column_1, column_2, column_3) VALUES (?, ?, ?)";
SQLiteStatement statement = db.compileStatement(sql);

int intValue = 57;
String stringValue1 = "hello";
String stringValue2 = "world";   
// corresponding to each question mark in the query
statement.bindLong(1, intValue); 
statement.bindString(2, stringValue1); 
statement.bindString(3, stringValue2);

long rowId = statement.executeInsert();

现在这工作得很好,但我在这里发现的问题是我必须非常小心地将正确的数据绑定到相应的索引。一个简单的索引交换会给我一个错误。

另外假设将来我的column_2 从表中删除,那么我将不得不更改column_2 索引之后的所有索引,否则该语句将不起作用。如果我只有 3 列,这似乎微不足道。想象一下,如果一个表有 10-12 个(甚至更多)列并且第 2 列被删除。我将不得不更新所有后续列的索引。整个过程似乎效率低下且容易出错。

有没有一种优雅的方式来处理这一切

编辑:我为什么要使用 SQLiteStatement ?检查这个:Improve INSERT-per-second performance of SQLite?

【问题讨论】:

标签: android sqlite sql-insert


【解决方案1】:

插入可以通过ContentValues:

ContentValues cv = new ContentValues();
cv.put("column_1", 57);
cv.put("column_2", "hello");
cv.put("column_3", "world");
long rowId = db.insertOrThrow("table_name", null, cv);

但在一般情况下,最正确的方法是使用named parameters。但是,Android 数据库 API 不支持这些。

如果您真的想使用SQLiteStatement,请编写您自己的帮助函数,该函数从列列表构造它并负责将其与实际数据匹配。您还可以编写自己的 bindXxx() 包装器,将先前保存的列名映射到参数索引。

【讨论】:

    【解决方案2】:

    您可以将 ContentValues 与 beginTransaction 一起使用到 SQLite 中,这非常简单并且比准备好的语句更快

    为此,您必须事先创建 ContentValues 数组或在循环中创建 Content 值对象。并传递给插入方法。这个解决方案可以解决你的两个问题。

    mDatabase.beginTransaction();
        try {
            for (ContentValues cv : values) {
                long rowID = mDatabase.insert(table, " ", cv);
                if (rowID <= 0) {
                    throw new SQLException("Failed to insert row into ");
                }
            }
            mDatabase.setTransactionSuccessful();
            count = values.length;
        } finally {
            mDatabase.endTransaction();
        }
    

    【讨论】:

    • 无论我们如何使用 SQL 语句或 ContentValues 将数据放入数据库对象,我们都在使用 Transaction,ContentValues 是将我们的数据放入 Sqlite 的标准方法,因为 Sqlite 的预定义方法接受 ContentValues 对象。
    • 请在此链接中找到更多详细信息:outofwhatbox.com/blog/2010/12/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-17
    • 1970-01-01
    • 2016-01-07
    • 2015-12-29
    • 1970-01-01
    相关资源
    最近更新 更多