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. 返回json格式的数据

  2. Linux 下eval命令揭秘

    eval 命令中文意思是“重新计算求出参数内容”,该命令大致有以下几个作用 将变量名替换后并执行 beautifulsoup4- Desktop Documents hc.war lxml- mybl ...

  3. hdu 4790 数学

    /* 题意:给你二个区间[a,b]和[c,d] 分别从中选一个数x和y使的(x+y)%p=m; 可以这样来求,先求出(0->b和0->d区间段的值)-(区间0->a-1和0-> ...

  4. 2016 Multi-University Training Contest 7 solutions BY SYSU

    Ants 首先求出每个点的最近点. 可以直接对所有点构造kd树,然后在kd树上查询除本身以外的最近点,因为对所有点都求一次,所以不用担心退化. 也可以用分治做,同样是O(NlogN)的复杂度. 方法是 ...

  5. webmagic使用手册

    https://my.oschina.net/flashsword/blog/180623 重点 SeleniumDownloader 对于一些Javascript动态加载的网页,仅仅使用http模拟 ...

  6. P2839 畅通工程

    P2839 畅通工程 题目描述 某省调查城镇交通状况,得到现有城镇道路统计表,表中列出了每条道路直接连通的城镇.省政府“畅通工程”的目标是使全省任何两个城镇间都可以实现交通(但不一定有直接的道路相连, ...

  7. GO语言 --socket.io

    socket.io是对websocket的封装以及扩展, 可以跨平台使用, 具体可看官网.. GO语言实现: package main import ( "github.com/googol ...

  8. Meteor软件包管理

    Meteor 提供数千种开发应用程序,您可以使用社区包. 添加软件包 您可以查看Meteor官方包服务器: 点击这里. 只搜索你需要的包,并在命令提示符窗口中添加它. 例如,想使用 http 包添加到 ...

  9. linux 下shell脚本执行多个命令的方法

    1.每个命令之间用;隔开说明:各命令的执行给果,不会影响其它命令的执行.换句话说,各个命令都会执行,但不保证每个命令都执行成功. 2.每个命令之间用&&隔开说明:若前面的命令执行成功, ...

  10. vue 获取当前时间 格式YYYY-MM-DD

    函数封装: /** * 获取当前时间 * 格式YYYY-MM-DD */ Vue.prototype.getNowFormatDate = function() { var date = new Da ...