android - 在 SQLite 查询中用 where 条件插入或替换多行

标签 android android-sqlite bulkinsert

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

我的表格:

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

enter image description here

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/

相关文章:

android - 如何使用 CursorLoader 进行多个串行数据库查询

android - 如何检查 SQLiteDatabase .replace() 是否成功?

c# - 什么是带有事务的 mongo 4.4 批量大小?

ruby-on-rails - 如何使用 rails 事件记录批量插入所有嵌套属性

performance - mongodb 插入时 Node 应用程序不工作

Android 6.0 DatePickerDialog 主题

android - 删除操作栏下的阴影

java - 无法打开sqlite数据库,指定的目录或数据库文件不存在

java - Android:向图像添加框架

android - 在android中找到最短路径/距离的任何算法?