Android开发--SQLit嵌入式数据存储

一、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: AndroidSQLite
       BuildTarget:Android2.1
       Application name: SQLite嵌入式数据库
       Package name: com.changcheng.sqlite
       Create Activity: AndroidSQLite
       Min SDK Version:7
 
       2. Contact实体
  1. package com.changcheng.sqlite.entity;



  2. public class Contact {

  3.          private Integer _id;

  4.          private String name;

  5.          private String phone;

  6.         

  7.          public Contact() {

  8.                    super();

  9.          }



  10.          public Contact(String name, String phone) {

  11.                    this.name = name;

  12.                    this.phone = phone;

  13.          }



  14.          public Integer get_id() {

  15.                    return _id;

  16.          }



  17.          public void set_id(Integer id) {

  18.                    _id = id;

  19.          }



  20.          public String getName() {

  21.                    return name;

  22.          }



  23.          public void setName(String name) {

  24.                    this.name = name;

  25.          }



  26.          public String getPhone() {

  27.                    return phone;

  28.          }



  29.          public void setPhone(String phone) {

  30.                    this.phone = phone;

  31.          }



  32.          @Override

  33.          public String toString() {

  34.                    return "Contants [id=" + _id + ", name=" + name + ", phone=" + phone

  35.                                      + "]";

  36.          }

  37. }
  3.编写MyOpenHelper类
       MyOpenHelper继承自SQLiteOpenHelper类。我们需要创建数据表,必须重写onCreate(更新时重写onUpgrade方法)方法,在这个方法中创建数据表。
  1. package com.changcheng.sqlite;



  2. import android.content.Context;

  3. import android.database.sqlite.SQLiteDatabase;

  4. import android.database.sqlite.SQLiteOpenHelper;



  5. public class MyOpenHelper extends SQLiteOpenHelper {



  6.          private static final String name = "contants"; // 数据库名称


  7.          private static final int version = 1; // 数据库版本




  8.          public MyOpenHelper(Context context) {

  9.                    /**

  10.                     * CursorFactory指定在执行查询时获得一个游标实例的工厂类。 设置为null,则使用系统默认的工厂类。

  11.                     */

  12.                    super(context, name, null, version);

  13.          }



  14.          @Override

  15.          public void onCreate(SQLiteDatabase db) {

  16.                    // 创建contacts表,SQL表达式时提供的字段类型和长度仅为提高代码的可读性。


  17.                    db.execSQL("CREATE TABLE IF NOT EXISTS contacts("

  18.                                      + "_id integer primary key autoincrement,"

  19.                                      + "name varchar(20)," + "phone varchar(50))");

  20.          }



  21.          @Override

  22.          public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

  23.                    // 仅演示用,所以先删除表然后再创建。


  24.                    db.execSQL("DROP TABLE IF EXISTS contacts");

  25.                    this.onCreate(db);

  26.          }

  27. }
4.编写ContactsService类
       ContactsService类主要实现对业务逻辑和数据库的操作。
  1. package com.changcheng.sqlite.service;



  2. import java.util.ArrayList;

  3. import java.util.List;

  4. import android.content.Context;

  5. import android.database.Cursor;

  6. import com.changcheng.sqlite.MyOpenHelper;

  7. import com.changcheng.sqlite.entity.Contact;



  8. public class ContactsService {



  9.          private MyOpenHelper openHelper;



  10.          public ContactsService(Context context) {

  11.                    this.openHelper = new MyOpenHelper(context);

  12.          }



  13.          /**

  14.           * 保存

  15.           *

  16.           * @param contact

  17.           */

  18.          public void save(Contact contact) {

  19.                    String sql = "INSERT INTO contacts (name, phone) VALUES (?, ?)";

  20.                    Object[] bindArgs = { contact.getName(), contact.getPhone() };

  21.                    this.openHelper.getWritableDatabase().execSQL(sql, bindArgs);

  22.          }



  23.          /**

  24.           * 查找

  25.           *

  26.           * @param id

  27.           * @return

  28.           */

  29.          public Contact find(Integer id) {

  30.                    String sql = "SELECT _id,name, phone FROM contacts WHERE _id=?";

  31.                    String[] selectionArgs = { id + "" };

  32.                    Cursor cursor = this.openHelper.getReadableDatabase().rawQuery(sql,

  33.                                      selectionArgs);

  34.                    if (cursor.moveToFirst())

  35.                             return new Contact(cursor.getInt(0), cursor.getString(1), cursor

  36.                                                .getString(2));

  37.                    return null;

  38.          }



  39.          /**

  40.           * 更新

  41.           *

  42.           * @param contact

  43.           */

  44.          public void update(Contact contact) {

  45.                    String sql = "UPDATE contacts SET name=?, phone=? WHERE _id=?";

  46.                    Object[] bindArgs = { contact.getName(), contact.getPhone(),

  47.                                      contact.get_id() };

  48.                    this.openHelper.getWritableDatabase().execSQL(sql, bindArgs);

  49.          }



  50.          /**

  51.           * 删除

  52.           *

  53.           * @param id

  54.           */

  55.          public void delete(Integer id) {

  56.                    String sql = "DELETE FROM contacts WHERE _id=?";

  57.                    Object[] bindArgs = { id };

  58.                    this.openHelper.getReadableDatabase().execSQL(sql, bindArgs);

  59.          }



  60.          /**

  61.           * 获取记录数量

  62.           *

  63.           * @return

  64.           */

  65.          public long getCount() {

  66.                    String sql = "SELECT count(*) FROM contacts";

  67.                    Cursor cursor = this.openHelper.getReadableDatabase().rawQuery(sql,

  68.                                      null);

  69.                    cursor.moveToFirst();

  70.                    return cursor.getLong(0);

  71.          }



  72.          /**

  73.           * 获取分页数据

  74.           *

  75.           * @param startIndex

  76.           * @param maxCount

  77.           * @return

  78.           */

  79.          public List<Contact> getScrollData(long startIndex, long maxCount) {

  80.                    String sql = "SELECT _id,name,phone FROM contacts LIMIT ?,?";

  81.                    String[] selectionArgs = { String.valueOf(startIndex),

  82.                                      String.valueOf(maxCount) };

  83.                    Cursor cursor = this.openHelper.getReadableDatabase().rawQuery(sql,

  84.                                      selectionArgs);

  85.                    List<Contact> contacts = new ArrayList<Contact>();

  86.                    while (cursor.moveToNext()) {

  87.                             Contact contact = new Contact(cursor.getInt(0),

  88.                                                cursor.getString(1), cursor.getString(2));

  89.                             contacts.add(contact);

  90.                    }

  91.                    return contacts;

  92.          }



  93.          /**

  94.           * 获取分页数据,提供给SimpleCursorAdapter使用。

  95.           *

  96.           * @param startIndex

  97.           * @param maxCount

  98.           * @return

  99.           */

  100.          public Cursor getScrollDataCursor(long startIndex, long maxCount) {

  101.                    String sql = "SELECT _id,name,phone FROM contacts LIMIT ?,?";

  102.                    String[] selectionArgs = { String.valueOf(startIndex),

  103.                                      String.valueOf(maxCount) };

  104.                    Cursor cursor = this.openHelper.getReadableDatabase().rawQuery(sql,

  105.                                      selectionArgs);

  106.                    return cursor;

  107.          }

  108. }
5.编写测试类
       编写一个针对ContactsService的测试类,测试ContactsService类中的各个方法是否正确。
  1. package com.changcheng.sqlite.test;



  2. import java.util.List;

  3. import com.changcheng.sqlite.MyOpenHelper;

  4. import com.changcheng.sqlite.entity.Contact;

  5. import com.changcheng.sqlite.service.ContactsService;

  6. import android.database.Cursor;

  7. import android.test.AndroidTestCase;

  8. import android.util.Log;



  9. public class ContactsServiceTest extends AndroidTestCase {



  10.          private static final String TAG = "ContactsServiceTest";



  11.          // 测试创建表


  12.          public void testCreateTable() throws Throwable {

  13.                    MyOpenHelper openHelper = new MyOpenHelper(this.getContext());

  14.                    openHelper.getWritableDatabase();

  15.          }



  16.          // 测试save


  17.          public void testSave() throws Throwable {

  18.                    ContactsService contactsService = new ContactsService(this.getContext());

  19.                    Contact contact1 = new Contact(null, "tom", "13898679876");

  20.                    Contact contact2 = new Contact(null, "lili", "13041094909");

  21.                    Contact contact3 = new Contact(null, "jack", "13504258899");

  22.                    Contact contact4 = new Contact(null, "heary", "1335789789");

  23.                    contactsService.save(contact1);

  24.                    contactsService.save(contact2);

  25.                    contactsService.save(contact3);

  26.                    contactsService.save(contact4);

  27.          }



  28.          // 测试find


  29.          public void testFind() throws Throwable {

  30.                    ContactsService contactsService = new ContactsService(this.getContext());

  31.                    Contact contact = contactsService.find(1);

  32.                    Log.i(TAG, contact.toString());

  33.          }



  34.          // 测试update


  35.          public void testUpdate() throws Throwable {

  36.                    ContactsService contactsService = new ContactsService(this.getContext());

  37.                    Contact contact = contactsService.find(1);

  38.                    contact.setPhone("1399889955");

  39.                    contactsService.update(contact);

  40.          }



  41.          // 测试getCount


  42.          public void testGetCount() throws Throwable {

  43.                    ContactsService contactsService = new ContactsService(this.getContext());

  44.                    Log.i(TAG, contactsService.getCount() + "");

  45.          }



  46.          // 测试getScrollData


  47.          public void testGetScrollData() throws Throwable {

  48.                    ContactsService contactsService = new ContactsService(this.getContext());

  49.                    List<Contact> contacts = contactsService.getScrollData(0, 3);

  50.                    Log.i(TAG, contacts.toString());

  51.          }

  52.         

  53.          // 测试getScrollDataCursor


  54.          public void testGetScrollDataCursor() throws Throwable {

  55.                    ContactsService contactsService = new ContactsService(this.getContext());

  56.                    Cursor cursor = contactsService.getScrollDataCursor(0, 3);

  57.                    while (cursor.moveToNext()) {

  58.                             Contact contact = new Contact(cursor.getInt(0),

  59.                                                cursor.getString(1), cursor.getString(2));

  60.                             Log.i(TAG, contact.toString());

  61.                    }

  62.          }



  63. }
启用测试功能,不要忘记在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:
  1. <?xml version="1.0" encoding="utf-8"?>

  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

  3.          android:orientation="vertical" android:layout_width="fill_parent"

  4.          android:layout_height="fill_parent">

  5.          <!-- ListView -->

  6.          <ListView android:layout_width="fill_parent"

  7.                    android:layout_height="fill_parent" android:id="@+id/listView" />



  8. </LinearLayout>
在mail.xml所在目录里添加一个contactitem.xml:
  1. <?xml version="1.0" encoding="utf-8"?>

  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

  3.          android:layout_width="wrap_content" android:layout_height="wrap_content">



  4.          <!-- contact.id -->

  5.          <TextView android:layout_width="30dip" android:layout_height="wrap_content"

  6.                    android:textSize="20sp" android:id="@+id/tv_id" />



  7.          <!-- contact.name -->

  8.          <TextView android:layout_width="150dip" android:layout_height="wrap_content"

  9.                    android:textSize="20sp" android:layout_toRightOf="@id/tv_id"

  10.                    android:layout_alignTop="@id/tv_id" android:id="@+id/tv_name" />



  11.          <!-- contact.phone -->

  12.          <TextView android:layout_width="150dip" android:layout_height="wrap_content"

  13.                    android:textSize="20sp" android:layout_toRightOf="@id/tv_name"

  14.                    android:layout_alignTop="@id/tv_name" android:id="@+id/tv_phone" />



  15. </RelativeLayout>
编辑AndroidSQLite类:
  1. package com.changcheng.sqlite;



  2. import java.util.ArrayList;

  3. import java.util.HashMap;

  4. import java.util.List;

  5. import com.changcheng.sqlite.R;

  6. import com.changcheng.sqlite.entity.Contact;

  7. import com.changcheng.sqlite.service.ContactsService;

  8. import android.app.Activity;

  9. import android.database.Cursor;

  10. import android.os.Bundle;

  11. import android.view.View;

  12. import android.widget.AdapterView;

  13. import android.widget.ListView;

  14. import android.widget.SimpleAdapter;

  15. import android.widget.Toast;

  16. import android.widget.AdapterView.OnItemClickListener;



  17. public class AndroidSQLite extends Activity {

  18.          /** Called when the activity is first created. */

  19.          @Override

  20.          public void onCreate(Bundle savedInstanceState) {

  21.                    super.onCreate(savedInstanceState);

  22.                    setContentView(R.layout.main);

  23.                    // 获取分页数据


  24.                    ContactsService contactsService = new ContactsService(this);

  25.                    List<Contact> contacts = contactsService.getScrollData(0, 3);

  26.                    // 获取ListView


  27.                    ListView lv = (ListView) this.findViewById(R.id.listView);

  28.                    // 生成List<? extends Map<String, ?>>数据


  29.                    List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();

  30.                    for (Contact contact : contacts) {

  31.                             HashMap<String, Object> item = new HashMap<String, Object>();

  32.                             item.put("_id", contact.get_id());

  33.                             item.put("name", contact.getName());

  34.                             item.put("phone", contact.getPhone());

  35.                             data.add(item);

  36.                    }

  37.                    // 生成Adapter


  38.                    SimpleAdapter adapter = new SimpleAdapter(this, data,

  39.                                      R.layout.contactitem, new String[] { "_id", "name", "phone" },

  40.                                      new int[] { R.id.tv_id, R.id.tv_name, R.id.tv_phone });

  41.                    // 设置ListView适配器


  42.                    lv.setAdapter(adapter);

  43.                   

  44.                    // 为ListView添加事件


  45.                    lv.setOnItemClickListener(new OnItemClickListener() {



  46.                             @Override

  47.                             public void onItemClick(AdapterView<?> parent, View view,

  48.                                                int position, long id) {

  49.                                      HashMap<String, Object> item = (HashMap<String, Object>) parent

  50.                                                         .getItemAtPosition((int) id);

  51.                                      Toast.makeText(AndroidSQLite.this, item.get("name").toString(),

  52.                                                         1).show();

  53.                             }



  54.                    });

  55.          }

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



  2. import com.changcheng.sqlite.R;

  3. import com.changcheng.sqlite.service.ContactsService;

  4. import android.app.Activity;

  5. import android.database.Cursor;

  6. import android.os.Bundle;

  7. import android.widget.ListView;

  8. import android.widget.SimpleCursorAdapter;



  9. public class AndroidSQLite extends Activity {

  10.          /** Called when the activity is first created. */

  11.          @Override

  12.          public void onCreate(Bundle savedInstanceState) {

  13.                    super.onCreate(savedInstanceState);

  14.                    setContentView(R.layout.main);



  15.                    // 获取分页数据


  16.                    ContactsService contactsService = new ContactsService(this);

  17.                    Cursor cursor = contactsService.getScrollDataCursor(0, 3);

  18.                    // 获取ListView


  19.                    ListView lv = (ListView) this.findViewById(R.id.listView);

  20.                    // 创建Adapter


  21.                    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,

  22.                                      R.layout.contactitem, cursor, new String[] { "_id", "name",

  23.                                                         "phone" }, new int[] { R.id.tv_id, R.id.tv_name,

  24.                                                         R.id.tv_phone });

  25.                    // 设置ListView适配器


  26.                    lv.setAdapter(adapter);



  27.                    // 为ListView添加事件


  28.                    lv.setOnItemClickListener(new OnItemClickListener() {



  29.                             @Override

  30.                             public void onItemClick(AdapterView<?> parent, View view,

  31.                                                int position, long id) {

  32.                                      Cursor cursor = (Cursor) parent

  33.                                                         .getItemAtPosition((int) position);

  34.                                      Toast.makeText(AndroidSQLite.this, cursor.getString(1), 1)

  35.                                                         .show();

  36.                             }

  37.                    });

  38.          }

  39. }
OK,在Android中的SQLite操作总结结束!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值