2013-03-26 57 views
2

我需要一个SQLite查询插入或更新SQLite表中。在SQLite中插入或替换多行条件查询

MyTable的:

  1. 标识(主键和not null)
  2. 名称
  3. ******中国

enter image description here

预期查询:如果ID不存在,那么必须插入新行 和如果现有的行值被改变则插入多个行当更新行。

编辑1:

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

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

+0

只是一个可能帮助别人的笔记。它**完全可以通过“插入或替换”来获得批量命令(so .. values(...),(...),(...)等等)。 – Fattie 2017-02-28 15:18:18

+0

只是另一个可能帮助别人的注意事项:)有趣的是,性能测试表明,“插入或替换”比普通的“插入”慢得多(5%最差)。 – Fattie 2017-02-28 15:23:02

回答

0

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

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(); 
    } 
} 

这样,你得到批量插入/更新,这是相当有效率!

+0

多行不会与您的查询一起工作。我努力了。 http://stackoverflow.com/questions/1609637/is-it-possible-to-insert-multiple-rows-at-a-time-in-an-sqlite-database – Ponmalar 2013-03-26 16:12:27

+0

@Ponmalar Emm,我希望你有一些自定义类对象,您想要在本地sqlite数据库中写入/更新。所以批量插入/更新可以正常工作。在ArrayList中传递多个对象 – Roman 2013-03-26 16:14:51

+0

感谢您的回复。我从webview发送查询。在WebView内部,我将使用sDataBase.execSQL(查询)执行查询;所以我只需要一个查询 – Ponmalar 2013-03-26 16:17:34