inserting a large number of records with SQLiteStatement.
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.的更多相关文章
- 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 ...
- Local Databases with SQLiteOpenHelper
Overview For maximum control over local data, developers can use SQLite directly by leveraging SQLit ...
- 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 ...
- Flink Internals
https://cwiki.apache.org/confluence/display/FLINK/Flink+Internals Memory Management (Batch API) In ...
- ContentProvider官方教程(7)3种访问形式:批处理、异步访问、intent间接访问(临时URI权限)
Alternative Forms of Provider Access Three alternative forms of provider access are important in app ...
- Content Provider Basics ——Content Provider基础
A content provider manages access to a central repository of data. A provider is part of an Android ...
- SQL MySQL
SQL 结构化查询语言(英语:Structural Query Language,缩写:SQL),是一种特殊目的之编程语言,用于数据库中的标准数据查询语言. 各种通行的数据库系统在其实践过程中都对SQ ...
- Spring Data JPA Batch Insertion
转自:https://www.jeejava.com/spring-data-jpa-batch-insertion/ Spring Data JPA Batch Insertion will sho ...
- JDK源码分析(5)Vector
JDK版本 Vector简介 /** * The {@code Vector} class implements a growable array of * objects. Like an arra ...
随机推荐
- 【转】玩玩负载均衡---在window与linux下配置nginx
最近有些时间,开始接触负载均衡方面的东西,从硬件F5再到Citrix Netscalar.不过因为硬件的配置虽然不复杂,但昂贵的价格也让一般用户望而却步(十几万到几十万),所以只能转向nginx,sq ...
- python006 Python3 运算符
Python3 运算符什么是运算符?本章节主要说明Python的运算符.举个简单的例子 4 +5 = 9 . 例子中,4 和 5 被称为操作数,"+" 称为运算符.Python语言 ...
- 七牛云一站式 SSL 证书服务上线,即刻使用最多可省 7 万
2017 年 ,随着谷歌.苹果和腾讯对原 HTTP 的相继限制,全站 HTTPS 已经成为了当下趋势,所以安装 SSL 证书成为网站建设中必不可少的一步. 在 2016 年底,七牛云已经与 Trust ...
- linux awk常用命令【转载】
简介 awk是一个强大的文本分析工具,相对于grep的查找,sed的编辑,awk在其对数据分析并生成报告时,显得尤为强大.简单来说awk就是把文件逐行的读入,以空格为默认分隔符将每行切片,切开的部分再 ...
- sgu208:Toral Tickets(Pólya定理)
题意简述:给你N和M,对于一个N∗M的单面方格纸你能够对它的每 个个格子黑白染色.然后把方格纸的长边卷起来,卷成一个圆柱体,然后再把 两个短边形成的圆也接起来.形成一个游泳圈的形状(我们染的色仅仅在游 ...
- 基于Hexo + Git + Nginx的博客发布
进过上一篇<树莓派搭建私人服务器>,我们已经有一个私人服务器了,现在需要做点什么实际事情了,先搭一个博客分享自己的经验吧. 相关文章:1.<树莓派搭建私人服务器>(http:/ ...
- 使用Android SwipeRefreshLayout了解Android的嵌套滑动机制
SwipeRefreshLayout 是在Android Support Library, revision 19.1.0加入到support v4库中的一个下拉刷新控件,关于android的下拉刷新 ...
- 总结一下CSS定位
在CSS中,Position 属性经常会用到,主要是绝对定位和相对定位,简单的使用都没有问题,尤其嵌套起来,就会有些混乱,今记录总结一下,防止久而忘之 CSS position属性值 absolute ...
- iOS国际化:NSLocalizedString的使用
因为iOS和XCode版本号更新得太快的原因,导致网上非常多文章都失去了时效性,或许再过两三个月我这篇文章也将走上这条路,但起码能够让现阶段看到的人对iOS的国际化有个比較清楚的认识. NSLocal ...
- 【Android开发-4】进入实践,最喜欢折腾的计算器
前言:前面对项目文件有了感性认识.接下来我们就须要通过不断实践,对项目的文件有理性的认识. 曾经折腾Unity3d.IOS开发都是拿计算器开刀.所以这次Android开发实践也不例外,继续拿计算器折腾 ...