我需要一个 SQLite 查询来在 SQLite 表中插入或更新。
我的表格:
- Id(主键且不为空)
- 姓名
- 电话号码
Expected Query: If the Id is not present then have to insert a new row and If the existing row value is changed then update the row when inserting multiple row.
编辑1:
我已经发布了我在 Insert Multiple Rows in SQLite Error (error code = 1) 中尝试过的 INSERT 查询。就像我尝试过使用“插入或替换”。但它与 Firfox SQLite Manager 配合使用,不适用于 Android SQLite
。
我使用了sDataBase.execSQL(query)
来执行此查询。
最佳答案
试试这个:
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();
}
}
这样你就可以批量插入/更新,效率非常高!
关于android - 在 SQLite 查询中用 where 条件插入或替换多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15641770/