一、SQLite简介

在Android平台上,集成了一个嵌入式关系型数据库—SQLite,SQLite3支持 NULL、INTEGER、REAL(浮点数字)、TEXT(字符串文本)和BLOB(二进制对象)数据类型,虽然它支持的类型虽然只有五种,但实际上sqlite3也接受varchar(n)、char(n)、decimal(p,s) 等数据类型,只不过在运算或保存时会转成对应的五种数据类型。 SQLite最大的特点是你可以保存任何类型的数据到任何字段中,无论这列声明的数据类型是什么。例如:可以在Integer字段中存放字符串,或者在布尔型字段中存放浮点数,或者在字符型字段中存放日期型值。 但有一种情况例外:定义为INTEGER PRIMARY KEY的字段只能存储64位整数, 当向这种字段中保存除整数以外的数据时,将会产生错误。另外, SQLite 在解析CREATE TABLE 语句时,会忽略 CREATE TABLE 语句中跟在字段名后面的数据类型信息。

二、SQLite的CURD

Android提供了一个名为SQLiteDatabase的类,该类封装了一些操作数据库的API,使用该类可以完成对数据进行添加(Create)、查询(Retrieve)、更新(Update)和删除(Delete)操作(这些操作简称为CRUD)。对SQLiteDatabase的学习,我们应该重点掌握execSQL()和rawQuery()方法。 execSQL()方法可以执行insert、delete、update和CREATE TABLE之类有更改行为的SQL语句;rawQuery()方法可以执行select语句。SQLiteDatabase还专门提供了对应于添加、删除、更新、查询的操作方法:insert()、delete()、update()和query() 。这些方法实际上是给那些不太了解SQL语法的菜鸟使用的,对于熟悉SQL语法的程序员而言,直接使用execSQL()和rawQuery()方法执行SQL语句就能完成数据的添加、删除、更新、查询操作。

三、SQLite的事务管理

使用SQLiteDatabase的beginTransaction()方法可以开启一个事务,程序执行到endTransaction() 方法时会检查事务的标志是否为成功,如果为成功则提交事务,否则回滚事务。当应用需要提交事务,必须在程序执行到endTransaction()方法之前使用setTransactionSuccessful() 方法设置事务的标志为成功,如果不调用setTransactionSuccessful() 方法,默认会回滚事务。

三、SQLite创建、更新数据表

如果应用使用到了SQLite数据库,在用户初次使用软件时,需要创建应用使用到的数据库表结构及添加一些初始化记录,另外在软件升级的时候,也需要对数据表结构进行更新。在Android系统,为我们提供了一个名为SQLiteOpenHelper的类,该类用于对数据库版本进行管理,该类是一个抽象类,必须继承它才能使用。为了实现对数据库版本进行管理,SQLiteOpenHelper类有两种重要的方法,分别是onCreate(SQLiteDatabase db)和onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)

当调用SQLiteOpenHelper的getWritableDatabase()或者getReadableDatabase()方法获取用于操作数据库的SQLiteDatabase实例的时候,如果数据库不存在,Android系统会自动生成一个数据库,接着调用onCreate()方法,onCreate()方法在初次生成数据库时才会被调用,在onCreate()方法里可以生成数据库表结构及添加一些应用使用到的初始化数据。onUpgrade()方法在数据库的版本发生变化时会被调用,数据库的版本是由程序员控制的,假设数据库现在的版本是1,由于业务的需要,修改了数据库表的结构,这时候就需要升级软件,升级软件时希望更新用户手机里的数据库表结构,为了实现这一目的,可以把原来的数据库版本设置为2(或其他数值),并且在onUpgrade()方法里面实现表结构的更新。当软件的版本升级次数比较多,这时在onUpgrade()方法里面可以根据原版号和目标版本号进行判断,然后作出相应的表结构及数据更新。

getWritableDatabase()和getReadableDatabase()方法都可以获取一个用于操作数据库的SQLiteDatabase实例。但getWritableDatabase() 方法以读写方式打开数据库,一旦数据库的磁盘空间满了,数据库就只能读而不能写,倘若使用的是getWritableDatabase() 方法就会出错。getReadableDatabase()方法先以读写方式打开数据库,如果数据库的磁盘空间满了,就会打开失败,当打开失败后会继续尝试以只读方式打开数据库。

四、SQLite示例程序

我们编写一个对表(Contacts)进行的操作来演示SQLite的应用。

1.创建Android工程

Project name:AndroidSQLiteBuildTarget:Android2.1Application name:SQLite嵌入式数据库Package name:com.changcheng.sqliteCreate Activity:AndroidSQLiteMin SDK Version:7

 

       2. Contact实体

packagecom.changcheng.sqlite.entity;publicclassContact {privateInteger_id;privateStringname;privateStringphone;publicContact() {super();}publicContact(String name, String phone) {this.name= name;this.phone= phone;}publicInteger get_id() {return_id;}publicvoidset_id(Integer id) {_id= id;}publicString getName() {returnname;}publicvoidsetName(String name) {this.name= name;}publicString getPhone() {returnphone;}publicvoidsetPhone(String phone) {this.phone= phone;}@OverridepublicString toString() {return"Contants [id="+_id+", name="+name+", phone="+phone+"]";}
}

3.编写MyOpenHelper类

MyOpenHelper继承自SQLiteOpenHelper类。我们需要创建数据表,必须重写onCreate(更新时重写onUpgrade方法)方法,在这个方法中创建数据表。

packagecom.changcheng.sqlite;importandroid.content.Context;
importandroid.database.sqlite.SQLiteDatabase;
importandroid.database.sqlite.SQLiteOpenHelper;publicclassMyOpenHelperextendsSQLiteOpenHelper {privatestaticfinalStringname="contants";//数据库名称privatestaticfinalintversion= 1;//数据库版本publicMyOpenHelper(Context context) {/*** CursorFactory指定在执行查询时获得一个游标实例的工厂类。 设置为null,则使用系统默认的工厂类。*/super(context,name,null,version);}@OverridepublicvoidonCreate(SQLiteDatabase db) {//创建contacts表,SQL表达式时提供的字段类型和长度仅为提高代码的可读性。db.execSQL("CREATE TABLE IF NOT EXISTS contacts("+"_id integer primary key autoincrement,"+"name varchar(20),"+"phone varchar(50))");}@OverridepublicvoidonUpgrade(SQLiteDatabase db,intoldVersion,intnewVersion) {//仅演示用,所以先删除表然后再创建。db.execSQL("DROP TABLE IF EXISTS contacts");this.onCreate(db);}
}

4.编写ContactsService类

ContactsService类主要实现对业务逻辑和数据库的操作。

packagecom.changcheng.sqlite.service;importjava.util.ArrayList;
importjava.util.List;
importandroid.content.Context;
importandroid.database.Cursor;
importcom.changcheng.sqlite.MyOpenHelper;
importcom.changcheng.sqlite.entity.Contact;publicclassContactsService {privateMyOpenHelperopenHelper;publicContactsService(Context context) {this.openHelper=newMyOpenHelper(context);}/***保存**@paramcontact*/publicvoidsave(Contact contact) {String sql ="INSERT INTO contacts (name, phone) VALUES (?, ?)";Object[] bindArgs = { contact.getName(), contact.getPhone() };this.openHelper.getWritableDatabase().execSQL(sql, bindArgs);}/***查找**@paramid*@return*/publicContact find(Integer id) {String sql ="SELECT _id,name, phone FROM contacts WHERE _id=?";String[] selectionArgs = { id +""};Cursor cursor =this.openHelper.getReadableDatabase().rawQuery(sql,selectionArgs);if(cursor.moveToFirst())returnnewContact(cursor.getInt(0), cursor.getString(1), cursor.getString(2));returnnull;}/***更新**@paramcontact*/publicvoidupdate(Contact contact) {String sql ="UPDATE contacts SET name=?, phone=? WHERE _id=?";Object[] bindArgs = { contact.getName(), contact.getPhone(),contact.get_id() };this.openHelper.getWritableDatabase().execSQL(sql, bindArgs);}/***删除**@paramid*/publicvoiddelete(Integer id) {String sql ="DELETE FROM contacts WHERE _id=?";Object[] bindArgs = { id };this.openHelper.getReadableDatabase().execSQL(sql, bindArgs);}/***获取记录数量**@return*/publiclonggetCount() {String sql ="SELECT count(*) FROM contacts";Cursor cursor =this.openHelper.getReadableDatabase().rawQuery(sql,null);cursor.moveToFirst();returncursor.getLong(0);}/***获取分页数据**@paramstartIndex*@parammaxCount*@return*/publicList<Contact> getScrollData(longstartIndex,longmaxCount) {String sql ="SELECT _id,name,phone FROM contacts LIMIT ?,?";String[] selectionArgs = { String.valueOf(startIndex),String.valueOf(maxCount) };Cursor cursor =this.openHelper.getReadableDatabase().rawQuery(sql,selectionArgs);List<Contact> contacts =newArrayList<Contact>();while(cursor.moveToNext()) {Contact contact =newContact(cursor.getInt(0),cursor.getString(1), cursor.getString(2));contacts.add(contact);}returncontacts;}/***获取分页数据,提供给SimpleCursorAdapter使用。**@paramstartIndex*@parammaxCount*@return*/publicCursor getScrollDataCursor(longstartIndex,longmaxCount) {String sql ="SELECT _id,name,phone FROM contacts LIMIT ?,?";String[] selectionArgs = { String.valueOf(startIndex),String.valueOf(maxCount) };Cursor cursor =this.openHelper.getReadableDatabase().rawQuery(sql,selectionArgs);returncursor;}
}

       5.编写测试类

编写一个针对ContactsService的测试类,测试ContactsService类中的各个方法是否正确。

packagecom.changcheng.sqlite.test;importjava.util.List;
importcom.changcheng.sqlite.MyOpenHelper;
importcom.changcheng.sqlite.entity.Contact;
importcom.changcheng.sqlite.service.ContactsService;
importandroid.database.Cursor;
importandroid.test.AndroidTestCase;
importandroid.util.Log;publicclassContactsServiceTestextendsAndroidTestCase {privatestaticfinalStringTAG="ContactsServiceTest";//测试创建表publicvoidtestCreateTable()throwsThrowable {MyOpenHelper openHelper =newMyOpenHelper(this.getContext());openHelper.getWritableDatabase();}//测试savepublicvoidtestSave()throwsThrowable {ContactsService contactsService =newContactsService(this.getContext());Contact contact1 =newContact(null,"tom","13898679876");Contact contact2 =newContact(null,"lili","13041094909");Contact contact3 =newContact(null,"jack","13504258899");Contact contact4 =newContact(null,"heary","1335789789");contactsService.save(contact1);contactsService.save(contact2);contactsService.save(contact3);contactsService.save(contact4);}//测试findpublicvoidtestFind()throwsThrowable {ContactsService contactsService =newContactsService(this.getContext());Contact contact = contactsService.find(1);Log.i(TAG, contact.toString());}//测试updatepublicvoidtestUpdate()throwsThrowable {ContactsService contactsService =newContactsService(this.getContext());Contact contact = contactsService.find(1);contact.setPhone("1399889955");contactsService.update(contact);}//测试getCountpublicvoidtestGetCount()throwsThrowable {ContactsService contactsService =newContactsService(this.getContext());Log.i(TAG, contactsService.getCount() +"");}//测试getScrollDatapublicvoidtestGetScrollData()throwsThrowable {ContactsService contactsService =newContactsService(this.getContext());List<Contact> contacts = contactsService.getScrollData(0, 3);Log.i(TAG, contacts.toString());}//测试getScrollDataCursorpublicvoidtestGetScrollDataCursor()throwsThrowable {ContactsService contactsService =newContactsService(this.getContext());Cursor cursor = contactsService.getScrollDataCursor(0, 3);while(cursor.moveToNext()) {Contact contact =newContact(cursor.getInt(0),cursor.getString(1), cursor.getString(2));Log.i(TAG, contact.toString());}}}

启用测试功能,不要忘记在AndroidManifest.xml文件中加入测试环境。为application元素添加一个子元素:<uses-library android:name="android.test.runner"/>,为application元素添加一个兄弟元素:<instrumentation android:name="android.test.InstrumentationTestRunner"     android:targetPackage="com.changcheng.sqlite" android:label="Tests for My App" />。

SQLite数据库以单个文件存储,就像微软的Access数据库。有一个查看SQLite数据库文件的工具——SQLite Developer,我们可以使用它来查看数据库。Android将创建的数据库存放在”/data/data/ com.changcheng.sqlite/databases/contacts”,我们将它导出然后使用SQLite Developer打开。

       6.分页显示数据

我们在ContactsService类中,提供了一个获取分页数据的方法。我们将调用它获取的数据,使用ListView组件显示出来。

编辑mail.xml:

<?xmlversion="1.0" encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical" android:layout_width="fill_parent"android:layout_height="fill_parent"><!-- ListView --><ListViewandroid:layout_width="fill_parent"android:layout_height="fill_parent" android:id="@+id/listView" /></LinearLayout>

在mail.xml所在目录里添加一个contactitem.xml:

<?xmlversion="1.0" encoding="utf-8"?>
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="wrap_content" android:layout_height="wrap_content"><!-- contact.id --><TextViewandroid:layout_width="30dip" android:layout_height="wrap_content"android:textSize="20sp"android:id="@+id/tv_id" /><!-- contact.name --><TextViewandroid:layout_width="150dip" android:layout_height="wrap_content"android:textSize="20sp"android:layout_toRightOf="@id/tv_id"android:layout_alignTop="@id/tv_id" android:id="@+id/tv_name" /><!-- contact.phone --><TextViewandroid:layout_width="150dip" android:layout_height="wrap_content"android:textSize="20sp"android:layout_toRightOf="@id/tv_name"android:layout_alignTop="@id/tv_name" android:id="@+id/tv_phone" /></RelativeLayout>

编辑AndroidSQLite类:

packagecom.changcheng.sqlite;importjava.util.ArrayList;
importjava.util.HashMap;
importjava.util.List;
importcom.changcheng.sqlite.R;
importcom.changcheng.sqlite.entity.Contact;
importcom.changcheng.sqlite.service.ContactsService;
importandroid.app.Activity;
importandroid.database.Cursor;
importandroid.os.Bundle;
importandroid.view.View;
importandroid.widget.AdapterView;
importandroid.widget.ListView;
importandroid.widget.SimpleAdapter;
importandroid.widget.Toast;
importandroid.widget.AdapterView.OnItemClickListener;publicclassAndroidSQLiteextendsActivity {/** Called when the activity is first created. */@OverridepublicvoidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);//获取分页数据ContactsService contactsService =newContactsService(this);List<Contact> contacts = contactsService.getScrollData(0, 3);//获取ListViewListView lv = (ListView)this.findViewById(R.id.listView);//生成List<? extends Map<String, ?>>数据List<HashMap<String, Object>> data =newArrayList<HashMap<String, Object>>();for(Contact contact : contacts) {HashMap<String, Object> item =newHashMap<String, Object>();item.put("_id", contact.get_id());item.put("name", contact.getName());item.put("phone", contact.getPhone());data.add(item);}//生成AdapterSimpleAdapter adapter =newSimpleAdapter(this, data,R.layout.contactitem,newString[] {"_id","name","phone"},newint[] { R.id.tv_id, R.id.tv_name, R.id.tv_phone});//设置ListView适配器lv.setAdapter(adapter);//为ListView添加事件lv.setOnItemClickListener(newOnItemClickListener() {@OverridepublicvoidonItemClick(AdapterView<?> parent, View view,intposition,longid) {HashMap<String, Object> item = (HashMap<String, Object>) parent.getItemAtPosition((int) id);Toast.makeText(AndroidSQLite.this, item.get("name").toString(),1).show();}});}
}

上面编写的分页显示数据比较麻烦,Android为我们提供了一个SimpleCursorAdapter类。使用它可以方便的显示分页数据。将AndroidSQLite类修改为:

xpackage com.changcheng.sqlite;


import com.changcheng.sqlite.R;
import com.changcheng.sqlite.service.ContactsService;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;public class AndroidSQLite extends Activity {/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);// 获取分页数据ContactsService contactsService = new ContactsService(this);Cursor cursor = contactsService.getScrollDataCursor(0, 3);// 获取ListViewListView lv = (ListView) this.findViewById(R.id.listView);// 创建AdapterSimpleCursorAdapter adapter = new SimpleCursorAdapter(this,R.layout.contactitem, cursor, new String[] { "_id", "name","phone" }, new int[] { R.id.tv_id, R.id.tv_name,R.id.tv_phone });// 设置ListView适配器lv.setAdapter(adapter);// 为ListView添加事件lv.setOnItemClickListener(new OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> parent, View view,int position, long id) {Cursor cursor = (Cursor) parent.getItemAtPosition((int) position);Toast.makeText(AndroidSQLite.this, cursor.getString(1), 1).show();}});}
}

android下sqlite操作详解相关推荐

  1. Android中SQLite应用详解(转)

    上次我向大家介绍了SQLite的基本信息和使用过程,相信朋友们对SQLite已经有所了解了,那今天呢,我就和大家分享一下在Android中如何使用SQLite. 现在的主流移动设备像Android.i ...

  2. Android中SQLite应用详解

    http://blog.csdn.net/liuhe688/article/details/6715983/ 现在的主流移动设备像Android.iPhone等都使用SQLite作为复杂数据的存储引擎 ...

  3. android 命令使用详解,Android下pm 命令详解

    作者:Sam (甄峰) sam_code@hotmail.com Sam在看相关PackageManager代码时,无意中发现Android 下提供一个pm命令,通常放在/system/bin/下.这 ...

  4. Android下pm命令详解

    在看相关PackageManager代码时,无意中发现Android 下提供一个pm命令,通常放在/system/bin/下.这个命令与Package有关,且非常实用.所以研究之. 0. Usage: ...

  5. View的事件体系之三 android事件分发机制详解(下)

    接着上一篇来分析事件分发机制,在看了各位大牛的关于事件分发机制的分析后茅塞顿开,之前看过好几遍郭霖,弘扬以及玉刚大神关于事件体系的讲解,一直看不懂,比较模糊,最近复习时,看到一篇博文,写的相当精彩,看 ...

  6. java控制mac录音代码_操作详解丨如何用 Cybery 控制 mac OS系统下的录音软件(DAW)...

    原标题:操作详解丨如何用 Cybery 控制 mac OS系统下的录音软件(DAW) Cybery可以在各主流平台/操作系统下实现MIDI控制功能:mac OS(可通过蓝牙.USB线或者借助其它硬件连 ...

  7. linux系统下grub.cfg详解和实例操作

    linux系统下grub.cfg详解和实例操作 简介 grub是引导操作系统的程序,它会根据自己的配置文件,去引导内核,当内核被加载到内存以后,内核会根据grub配置文件中的配置,找到根分区所使用的文 ...

  8. Linux下Android ADB驱动安装详解

    Developing with cocos2d-x for android on Linux http://blog.plicatibu.com/developing-with-cocos2d-x-f ...

  9. 工程之星android版使用,安卓版工程之星软件网络1+1模式及网络cors连接操作详解...

    原标题:安卓版工程之星软件网络1+1模式及网络cors连接操作详解 现在,越来越多用户开始使用安卓版工程之星进行作业,科力达技术工程师总结了安卓版工程之星网络1+1模式及网络CORS连接方式操作步骤, ...

最新文章

  1. java web项目目录报错_netdevgirl.通过maven创建javaweb项目
  2. java socket聊天工具_java+socket 简易聊天工具
  3. manjaro21 linux安装vscode
  4. Java程序员面试时要注意的一些问题
  5. Qt文档阅读笔记-Multiple Inheritance Example 实例解析及Automatic Connections解析
  6. python2.7入门---内置函数
  7. 如何迅速掌握并提高linux运维技能
  8. java10 WeakHashMap
  9. Pycharm使用---Black代码格式化工具
  10. 利用ES4封装Windows10
  11. 数据库原理及应用(思维导图、索引、合集)
  12. 服务器宕机维护公告,服务器“宕机”的诊断方法
  13. 学习STM32的理由
  14. Cocoa -- 添加和移除开机启动项
  15. JavaFX Scene Builder 2.0 + IDEA 制作客户端界面
  16. “泰迪杯”挑战赛 - 通过数据挖掘技术实现道路缺陷自动识别
  17. 狂神css视频笔记1-15课
  18. VirtualBox 5.1.24神更新
  19. Project Euler Problem 66
  20. 基于形心的目标检测方法

热门文章

  1. ABB机器人socket通讯实时位置上传,中断触发
  2. 仪征市实验小学教师计算机课,仪征市“智慧课堂系列研讨活动”在我校成功举办...
  3. vmware桥接模式-无法内网通-克隆机要删除的文件-ssl
  4. 【电子杂志设计制作】云展网教程 | 编辑杂志的删除和停用功能
  5. 使用dede系统建设中英文双语网站详解
  6. 学霸如何用计算机表白,520,表白进行时!各科学霸们逆天的表白方式
  7. 项目部署到tomcat中startup.bat步骤
  8. [Python]编码声明:是coding:utf-8还是coding=urf-8呢
  9. scyllaDb在centos8上试用
  10. 几步教会你用solidworks实现小汽车的运动动画