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. UVALive 2957 Bring Them There

    Bring Them There Time Limit: 3000ms Memory Limit: 131072KB This problem will be judged on UVALive. O ...

  2. python3--产生偏移和元素:enumerate

    之前,我们讨论过通过range来产生字符串中元素的偏移值.而不是那些偏移值处的元素.不过,在有些程序中.我们两者都需要,要用的元素以及值个元素的偏移值.从传统意义来讲,这是简单的for循环,他同时也持 ...

  3. PTA 02-线性结构4 Pop Sequence (25分)

    题目地址 https://pta.patest.cn/pta/test/16/exam/4/question/665 5-3 Pop Sequence   (25分) Given a stack wh ...

  4. 关于如何使用Spring里@AliasFor注解进行注解的封装

    不知道大家每次使用Spring boot的时候有没有看过它启动类里 @SpringBootApplication这个注解呢?众所周知,这个注解是一个复合注解,但是注解是不能继承元注解的属性的,也就是说 ...

  5. 一段曲折的copy路程

    cp 的时候出现:-bash: /bin/cp: Argument list too longcp ./*.swf  /www/img/html/xxx/action/ 解决办法:find ./ -n ...

  6. Assigning to "id<CALayerDelegate> _Nullable" from incompatible type "ZXCapture *const __strong" 的警告提示信息

    该警告提示信息,是说,设置了代理对象,但是并没有继承它的代理.下图中,可以看出,警告信息提示我们没有继承“CALayerDelegate”的代理. 解决方法,很简单,(在 @interface 文件中 ...

  7. Linux 常用但较容易忘记的命令

    看死循环 strace -p pid 查看系统版本 cat /etc/issue 设置内核启动版本 /etc/lilo.conf , /boot/grub/grub.conf 设置启动模式  /etc ...

  8. Java中@SuppressWarnings注解用法(转)

    背景: J2SE提供的最后一个注解是@SuppressWarnings.该批注的作用是给编译器一条指令,告诉它对被批注的代码元素内部的某些警告保持静默. @SuppressWarnings注解允许您选 ...

  9. ArcGIS Engine三维动画开发 来自:http://www.iarcgis.com/?p=826

    ArcGIS Engine 三维开发 来自:http://www.iarcgis.com/?p=826 在三维中,经常使用的一个功能就是播放动画,也就是我们要对一条动画轨迹进行播放,而在ArcGIS ...

  10. 磁盘显示为GPT(保护分区)

    问题描述:PE进入系统,在计算机管理里面磁盘显示为GPT(保护分区).此时硬盘是不能重新分区或者格式化的. 解决思路:低版本的WIndows(PE)是不支持GPT分区的,我们需要使用系统自带的Disk ...