2

我需要一个 SQLite 查询来在 SQLite 表中插入或更新。

我的表:

  1. Id(主键且不为空)
  2. 姓名
  3. 电话号码

在此处输入图像描述

预期查询:如果 Id 不存在,则必须插入新行,如果现有行值已更改,则在插入多行时更新行。

编辑1:

我已经发布了我在Insert Multiple Rows in SQLite Error (error code = 1) 中尝试过的 INSERT 查询。就像我尝试过使用“插入或替换”一样。但它是working with Firfox SQLite Manager Not working with Android SQLite

我曾经sDataBase.execSQL(query)执行过这个查询。

4

2 回答 2

2

尝试这个:

String sql = "INSERT OR REPLACE INTO MyTable (Name, PhoneNumber) VALUES (?,?)";
SQLiteStatement st = db.compileStatement(sql);

并编写或更新:

    public void writeOrUpdateData(ArrayList<MyClass> data) {
    try {

        db.beginTransaction();

        for(int i = 0; i < data.size(); i++) {

            st.clearBindings();
            st.bindLong(1, data.get(i).getName());
            st.bindString(2, data.get(i).getPhoneNumber);
            st.executeInsert();

        }

        db.setTransactionSuccessful();

    } 
    catch(Exception e) {} 
    finally {
        db.endTransaction();
    }
}

这样您就可以获得批量插入/更新,这非常有效!

于 2013-03-26T16:10:35.623 回答
0

我只在 Firefox SQLite Manager 中创建了带有主键的数据库。我在 Android 的 SQLite 数据库中错过了这个。现在我有created database with PRIMARY KEY and NOT NULL现在工作正常

于 2013-03-27T11:35:23.573 回答