2012-04-15 50 views
1

当我第一次运行应用程序时,我想要创建一个表格并在表格中输入一些行。这样做的,我写了这段代码,它是工作的罚款:在表格中输入多行的最简单方法

  //Creating the table 
     db.execSQL(MRM_BOOKING_LOGIN_TABLE_CREATE);   
     //Setting the values in the table 
     ContentValues contentValuesLogin = new ContentValues(); 
     contentValuesLogin.put(USER_ID, "asdf"); 
     contentValuesLogin.put(PASSWORD, "1234"); 
     //Inserting a row in the table 
     db.insert(MRM_BOOKING_LOGIN_TABLE, null, contentValuesLogin); 

但我想在表格中输入至少15至20行。每次插入一行后,我会清除ContentValues对象(或者创建ContentValues的另一个对象),并在新创建的表中输入另一行,这是一个好主意吗?这样,代码行也会增加很多。我相信可能有其他更好的替代方法来做同样的事情。请建议

问候,

+0

我是假设你的15-20行已硬编码(用户ID和密码是提前知道)值或者他们通过其他方式产生的?如果它们是硬编码的,则可以使用资源字符串数组并对其进行循环。 – 2012-04-15 02:53:55

回答

-1

可以使用ContentResolver.bulkInsert (Uri url, ContentValues[] values)插入多行。

的更多信息可以从这里可得:

Insertion of thousands of contact entries using applyBatch is slow

希望这会帮助你。

+0

我想这可能是有效的** ContentResolver **,但不是** SQLite **直接 – waqaslam 2012-04-15 02:48:33

+0

它也可以用于SQLIte。 – UVM 2012-04-15 02:50:11

+0

好吧,我会去批量插入。谢谢 – user182944 2012-04-15 03:17:41

2

我认为,通过db.insert插入多个记录的唯一方法是使用循环。将它与SQLite 交易结合在一起,它将加快此过程。

+0

忘记了db.insert的时间,告诉我一些其他的方法来做同样的事情。 – user182944 2012-04-15 03:14:12

+0

然后使用** DatabaseUtils.InsertHelper **。阅读此http://www.outofwhatbox.com/blog/2010/12/android-using-databaseutils-inserthelper-for-faster-insertions-into-sqlite-database/ – waqaslam 2012-04-15 03:18:55

+0

好吧,我会看看它。谢谢 – user182944 2012-04-15 03:37:53

2

示例代码:

try { 
      // open the database 
      db.beginTransaction(); 

      for (your objects) { 
       ContentValues cv = new ContentValues(); 
       cv.put(COL1, obj.p1); 
       cv.put(COL2, obj.p2); 
       //..... 

       long id = db.insertOrThrow(DATABASE_TABLE, COL_Id, cv); 
      } 

      db.setTransactionSuccessful(); 
} catch (Exception e) { 
      throw e; 
     } finally { 
      db.endTransaction(); 
      // close database 
     } 
相关问题