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. 【转】关于大型网站技术演进的思考(二十一)--网站静态化处理—web前端优化—下【终篇】(13)

    本篇继续web前端优化的讨论,开始我先讲个我所知道的一个故事,有家大型的企业顺应时代发展的潮流开始投身于互联网行业了,它们为此专门设立了一个事业部,不过该企业把这个事业部里的人事成本,系统运维成本特别 ...

  2. 【数学+枚举】OpenJ_POJ - C17J Pairs

    https://vjudge.net/contest/171652#problem/J [题意] 问有多少个正整数对(x,y),使得存在正整数p,q满足 1 <= T <= 15 1 &l ...

  3. 跨域访问sessionid不一致问题

    在开发过程中遇到这么一个问题,让我花了一个下午的大好时光才解决.但是解决玩之后,发现那么的容易.就是查找资料的时候很费劲.这里把问题记录一下. 问题的产生 流程是这样的,要做一个用户登录的接口.在登录 ...

  4. 《TCP/IP详解卷1:协议》——第5章 RARP:逆地址解析协议(转载)

    1.引言 具有本地磁盘的系统引导时,一般是从磁盘上的配置文件中读取IP地址.但是无盘机,如X终端或无盘工作站,则需要采用其他方法来获得IP地址. 网络上的每个系统都具有唯一的硬件地址,它是由网络接口生 ...

  5. AndroidUI的基本结构

    AndroidUI的基本结构 创建时间: 2013-9-13 11:05 更新时间: 2013-9-13 11:05

  6. POJ 2240 【这题貌似可以直接FLOYD 屌丝用SPFA通过枚举找正权值环 顺便学了下map】

    题意: 给了n种硬币的名称,给了m种硬币间的转换关系. 从任意兑换地点开始兑换,看是否能够通过兑换的方式增加金钱. 思路: 用SPFA不断对各个点进行松弛操作,寻找正权值的环.如果找到则输出Yes. ...

  7. 七天从零基础学习android(3)--实现过程

    首先这是我对自己编写程序的认识,要实现一个程序,根据之前编写C++的经验,要对所编写的软件有一个模糊的了解. 一个记账本软件,要实现的过程是,添加收支,显示本日,本月或本年的收支状态.然而基于是完全没 ...

  8. git获取远程分支

    运行 git checkout -b local-branchname origin/remote_branchname  就可以将远程分支映射到本地命名为local-branchname  的一分支 ...

  9. 关于MSSQL的decimal(numeric)、money、float的使用以及区别

    decimal(numeric).money.float(real) 都是MSSQL中的浮点类型的数据类型. 按存储的范围进行排序 float(real) decimal(numeric) money ...

  10. [转] SQL SERVER 2008 R2 安装中的账户设置问题

    故纸堆 原文:SQL SERVER 2008安装中设置账户的问题,2013-7 在安装SQL Server 2008数据库服务器的时候,服务器有可能处于以下几种环境中: ①工作组环境下的服务器 (Wo ...