在SQLite Query中的where where条件中插入或替换多行

时间:2013-03-26 16:04:30

标签: android android-sqlite bulkinsert

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

MyTable的:

  1. ID (主键,非空)
  2. 命名
  3. ******中国
  4. enter image description here

      

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

    编辑1:

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

    我使用sDataBase.execSQL(query)来执行此查询。

2 个答案:

答案 0 :(得分: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();
    }
}

通过这种方式,您可以获得批量插入/更新,这非常有效!

答案 1 :(得分:0)

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

相关问题