Below is a demo application I wrote that creates 100 records programmatically, inserts them using one of two methods, and then displays the time the operation took on the display. You can follow along with the step-by-step tutorial or download and import the entire project directly into Eclipse.

1. Start a new Android project in Eclipse. Target Android 2.2 or higher.

2. In the /res/layout folder, open activity_main.xml. You will use a linear layout, a couple of buttons, and a text view.

  1. activity_main.xml
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. android:layout_width="match_parent"
  3. android:layout_height="match_parent"
  4. android:orientation="vertical">
  5.  
  6. <TextView
  7. android:layout_width="wrap_content"
  8. android:layout_height="wrap_content"
  9. android:text="Bulk Insert Demonstration" />
  10.  
  11. <Button
  12. android:layout_width="wrap_content"
  13. android:layout_height="wrap_content"
  14. android:text="Standard Insert"
  15. android:id="@+id/standard_insert_button"/>
  16.  
  17. <Button
  18. android:layout_width="wrap_content"
  19. android:layout_height="wrap_content"
  20. android:text="Bulk Insert"
  21. android:id="@+id/bulk_insert_button"/>
  22.  
  23. <TextView
  24. android:layout_width="wrap_content"
  25. android:layout_height="wrap_content"
  26. android:text="Execution Time: xxx"
  27. android:id="@+id/exec_time_label"/>
  28.  
  29. </LinearLayout>

3. In the /src/MainActivity.java file, let's start by adding a few class variables, initializing an empty database, and wiring up the buttons.

  1. MainActivity.java
  1. package com.authorwjf.bulkinsertdemo;
  2.  
  3. import android.os.Bundle;
  4. import android.view.View;
  5. import android.view.View.OnClickListener;
  6. import android.widget.TextView;
  7. import android.app.Activity;
  8. import android.content.ContentValues;
  9. import android.database.sqlite.SQLiteDatabase;
  10. import android.database.sqlite.SQLiteStatement;
  11.  
  12. public class MainActivity extends Activity implements OnClickListener {
  13.  
  14. private static final String SAMPLE_DB_NAME = "MathNerdDB";
  15. private static final String SAMPLE_TABLE_NAME = "MulitplicationTable";
  16. private SQLiteDatabase sampleDB;
  17.  
  18. @Override
  19. protected void onCreate(Bundle savedInstanceState) {
  20. super.onCreate(savedInstanceState);
  21. setContentView(R.layout.activity_main);
  22. initDB();
  23. findViewById(R.id.standard_insert_button).setOnClickListener(this);
  24. findViewById(R.id.bulk_insert_button).setOnClickListener(this);
  25. }
  26.  
  27. private void initDB() {
  28. sampleDB = this.openOrCreateDatabase(SAMPLE_DB_NAME, MODE_PRIVATE, null);
  29. sampleDB.execSQL("CREATE TABLE IF NOT EXISTS " +
  30. SAMPLE_TABLE_NAME +
  31. " (FirstNumber INT, SecondNumber INT," +
  32. " Result INT);");
  33. sampleDB.delete(SAMPLE_TABLE_NAME, null, null);
  34. }
  35.  
  36. @Override
  37. public void onClick(View v) {
  38. sampleDB.delete(SAMPLE_TABLE_NAME, null, null);
  39. long startTime = System.currentTimeMillis();
  40. if (v.getId()==R.id.standard_insert_button) {
  41. insertOneHundredRecords();
  42. } else {
  43. bulkInsertOneHundredRecords();
  44. }
  45. long diff = System.currentTimeMillis() - startTime;
  46. ((TextView)findViewById(R.id.exec_time_label)).setText("Exec Time: "+Long.toString(diff)+"ms");
  47. }
  48.  
  49. @Override
  50. protected void onDestroy() {
  51. sampleDB.close();
  52. super.onDestroy();
  53. }
  54.  
  55. }

4. Add our two database insert functions: one based on content values and the other on SQLite transactions.

  1. private void insertOneHundredRecords() {
  2. for (int i = 0; i<100; i++) {
  3. ContentValues values = new ContentValues();
  4. values.put("FirstNumber", i);
  5. values.put("SecondNumber", i);
  6. values.put("Result", i*i);
  7. sampleDB.insert(SAMPLE_TABLE_NAME,null,values);
  8. }
  9. }
  10.  
  11. private void bulkInsertOneHundredRecords() {
  12. String sql = "INSERT INTO "+ SAMPLE_TABLE_NAME +" VALUES (?,?,?);";
  13. SQLiteStatement statement = sampleDB.compileStatement(sql);
  14. sampleDB.beginTransaction();
  15. for (int i = 0; i<100; i++) {
  16. statement.clearBindings();
  17. statement.bindLong(1, i);
  18. statement.bindLong(2, i);
  19. statement.bindLong(3, i*i);
  20. statement.execute();
  21. }
  22. sampleDB.setTransactionSuccessful();
  23. sampleDB.endTransaction();
  24. }

Now you are ready to try the application on the emulator (this is not production code). I'm purposely performing all the work on the UI, so it becomes painfully obvious how long the operations are taking. I still think you will agree there is more than enough code to make a convincing argument for using the transactional inserts. And since they say a picture is worth a thousand words, take a look at these illustrations.

Pressing the first button, our application reports the insert operations took just over 1600 milliseconds (Figure A).

Figure A

The bulk insert method was able to initialize the same table in under 100 milliseconds (Figure B).

Figure B

It's a phenomenal speed gain in exchange for a very minor increase in code complexity. Now that I've experienced these speed gains firsthand, I can't imagine many scenarios in which I won't be use bulk inserts going forward.

inserting a large number of records with SQLiteStatement.的更多相关文章

  1. How to delete a large number of data in SharePoint for List when refreshing data?

    Preface Recently thequestion was asked in the newsgroups about deleting a large number of itemsfrom ...

  2. Local Databases with SQLiteOpenHelper

    Overview For maximum control over local data, developers can use SQLite directly by leveraging SQLit ...

  3. Searching External Data in SharePoint 2010 Using Business Connectivity Services

    from:http://blogs.msdn.com/b/ericwhite/archive/2010/04/28/searching-external-data-in-sharepoint-2010 ...

  4. Flink Internals

    https://cwiki.apache.org/confluence/display/FLINK/Flink+Internals   Memory Management (Batch API) In ...

  5. ContentProvider官方教程(7)3种访问形式:批处理、异步访问、intent间接访问(临时URI权限)

    Alternative Forms of Provider Access Three alternative forms of provider access are important in app ...

  6. Content Provider Basics ——Content Provider基础

    A content provider manages access to a central repository of data. A provider is part of an Android ...

  7. SQL MySQL

    SQL 结构化查询语言(英语:Structural Query Language,缩写:SQL),是一种特殊目的之编程语言,用于数据库中的标准数据查询语言. 各种通行的数据库系统在其实践过程中都对SQ ...

  8. Spring Data JPA Batch Insertion

    转自:https://www.jeejava.com/spring-data-jpa-batch-insertion/ Spring Data JPA Batch Insertion will sho ...

  9. JDK源码分析(5)Vector

    JDK版本 Vector简介 /** * The {@code Vector} class implements a growable array of * objects. Like an arra ...

随机推荐

  1. CDOJ 1220 The Battle of Guandu

    The Battle of Guandu Time Limit: 6000/3000MS (Java/Others)     Memory Limit: 65535/65535KB (Java/Oth ...

  2. Java实战及解析 — Maven快速入门

    五分钟快速入门 mvn --version mvn archetype:generate -DgroupId=com.mycompany.app -DartifactId=my-app -Darche ...

  3. NYOJ27水池数目,类似于FZU1008最大黑区域,简单搜索题~~~

    水池数目 时间限制:3000 ms  |  内存限制:65535 KB 难度:4 描述 南阳理工学院校园里有一些小河和一些湖泊,现在,我们把它们通一看成水池,假设有一张我们学校的某处的地图,这个地图上 ...

  4. oracle 9i/10g/11g(11.2.0.3)安装包和PATCH下载地址汇总

    今天上PUB看见一位热心人汇总了这么个地址列表,转发来空间: 把下面的地址复制到讯雷里就可以下载. -------------------------------------------------- ...

  5. vscode 打开新文件覆盖窗口,始终显示一个窗口

    一直在使用vscode 编辑器,里面的扩展用的比较舒服,但是最近遇到一个小问题,一直也没有找好的解决办法,今天无意中把问题给解决了.具体如下 之前使用编辑器,可以同时打开多个文件,而且是多窗口展示的, ...

  6. codevs——3064 求和

    3064 求和  时间限制: 1 s  空间限制: 32000 KB  题目等级 : 青铜 Bronze 题解  查看运行结果     题目描述 Description 输入一个数x(x <= ...

  7. redis 实际应用中的缓存作用(转)

    有人说互联网用户是用脚投票的,这句话其实也从侧面说明了,用户体验是多么的重要:这就要求在软件架构设计时,不但要注重可靠性.安全性.可扩展性以及可维护性等等的一些指标,更要注重用户的体验,用户体验分很多 ...

  8. 【nginx】【转】Nginx启动框架处理流程

    Nginx启动过程流程图: ngx_cycle_t结构体: Nginx的启动初始化在src/core/nginx.c的main函数中完成,当然main函数是整个Nginx的入口,除了完成启动初始化任务 ...

  9. 【Git使用具体解释】Egit的经常使用操作具体解释

    经常使用操作 操作 说明 Fetch 从远程获取最新版本号到本地,不会自己主动merge Merge 能够把一个分支标签或某个commit的改动合并如今的分支上 Pull 从远程获取最新版本号并mer ...

  10. android 自己定义水平和圆形progressbar 仅仅定义一些style就能够

    效果图: watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/diss ...