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.

activity_main.xml 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"> <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bulk Insert Demonstration" /> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Standard Insert"
android:id="@+id/standard_insert_button"/> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bulk Insert"
android:id="@+id/bulk_insert_button"/> <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Execution Time: xxx"
android:id="@+id/exec_time_label"/> </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.

MainActivity.java
package com.authorwjf.bulkinsertdemo;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.app.Activity;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement; public class MainActivity extends Activity implements OnClickListener { private static final String SAMPLE_DB_NAME = "MathNerdDB";
private static final String SAMPLE_TABLE_NAME = "MulitplicationTable";
private SQLiteDatabase sampleDB; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initDB();
findViewById(R.id.standard_insert_button).setOnClickListener(this);
findViewById(R.id.bulk_insert_button).setOnClickListener(this);
} private void initDB() {
sampleDB = this.openOrCreateDatabase(SAMPLE_DB_NAME, MODE_PRIVATE, null);
sampleDB.execSQL("CREATE TABLE IF NOT EXISTS " +
SAMPLE_TABLE_NAME +
" (FirstNumber INT, SecondNumber INT," +
" Result INT);");
sampleDB.delete(SAMPLE_TABLE_NAME, null, null);
} @Override
public void onClick(View v) {
sampleDB.delete(SAMPLE_TABLE_NAME, null, null);
long startTime = System.currentTimeMillis();
if (v.getId()==R.id.standard_insert_button) {
insertOneHundredRecords();
} else {
bulkInsertOneHundredRecords();
}
long diff = System.currentTimeMillis() - startTime;
((TextView)findViewById(R.id.exec_time_label)).setText("Exec Time: "+Long.toString(diff)+"ms");
} @Override
protected void onDestroy() {
sampleDB.close();
super.onDestroy();
} }

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

private void insertOneHundredRecords() {
for (int i = 0; i<100; i++) {
ContentValues values = new ContentValues();
values.put("FirstNumber", i);
values.put("SecondNumber", i);
values.put("Result", i*i);
sampleDB.insert(SAMPLE_TABLE_NAME,null,values);
}
} private void bulkInsertOneHundredRecords() {
String sql = "INSERT INTO "+ SAMPLE_TABLE_NAME +" VALUES (?,?,?);";
SQLiteStatement statement = sampleDB.compileStatement(sql);
sampleDB.beginTransaction();
for (int i = 0; i<100; i++) {
statement.clearBindings();
statement.bindLong(1, i);
statement.bindLong(2, i);
statement.bindLong(3, i*i);
statement.execute();
}
sampleDB.setTransactionSuccessful();
sampleDB.endTransaction();
}

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. Javascript拼接HTML字符串的方法列举及思路

    转载过来,去掉一些废话吧. 目标: 方便的拼接字符串,不使用让人眼晕的+=.使用过程如下: 1,先创建一个作为“模板”的字符串,如:’My name is ${name},I\’m ${age}.’ ...

  2. Oracle常用内置数据表查询

    Oracle 查询库中所有表名.字段名.字段名说明,查询表的数据条数.表名.中文表名. 查询所有表名:select t.table_name from user_tables t;查询所有字段名:se ...

  3. python多线程--线程同步

    如果多个线程共同对某个数据修改,则可能出现不可预料的结果,为了保证数据的正确性,需要对多个线程进行同步. 使用Thread对象的Lock和Rlock可以实现简单的线程同步,这两个对象都有acquire ...

  4. java中filter的用法

    filter过滤器主要使用于前台向后台传递数据是的过滤操作.程度很简单就不说明了,直接给几个已经写好的代码: 一.使浏览器不缓存页面的过滤器 Java代码   import javax.servlet ...

  5. Genymotion 常见问题Unable to configure the network adapter for the virtual device解决

    Genymotion 常见问题Unable to configure the network adapter for the virtual device解决 参考:http://www.pczhis ...

  6. Open Judge 3339 List

    3339:List 总时间限制:  4000ms 内存限制:  65536kB 描述 写一个程序完成以下命令:new id ——新建一个指定编号为id的序列(id<10000)add id nu ...

  7. eslint (js代码检查)

    eslint 是一个应用广泛的javascript代码检查工具. 能检测变量名重复等等... 1.安装 npm install -g eslint 2.初始化 会在当前目录下生成一个.eslintrc ...

  8. 洛谷——P2256 一中校运会之百米跑

    P2256 一中校运会之百米跑 题目背景 在一大堆秀恩爱的**之中,来不及秀恩爱的苏大学神踏着坚定(?)的步伐走向了100米跑的起点.这时苏大学神发现,百米赛跑的参赛同学实在是太多了,连体育老师也忙不 ...

  9. Ubuntu 16.04安装Fiddler抓包工具(基于Mono,且会有BUG)

    说明:Fiddler官方提供了Mono版本的,但是只有2014版本的,不是最新的,并且运行期间会有BUG,比如界面错乱卡死等等,但是勉强能代理,抓SSL的包,如果使用了要做好心理准备.将就一下还是可以 ...

  10. Java数组操作方法收集(快速判断某个值在这个数组中)

    Java数组操作最高效的方式是循环取值,如果转换成集合那么就会分配内存,效率不如前者,但是方法多,需要在性能调优上去权衡.切记:数组是数组,集合是集合. 下面是收集最常用的数组转成集合的操作方法: i ...