Android应用开发之SQLite数据库


SQLite简介

SQLite是一个开源的嵌入式关系数据库,它在 2000 年由 D.Richard Hipp 发布,它可以减少应用程序管理数据的开销 , SQLite 可移植性好 、很容易使用 、 很小 、 高效而且可靠 。目前在 Android 系统中集成的是 SQLite3 版本 , SQLite 不支持静态数据类型 , 而是使用列关系。 这意味着它的数据类型不具有表列属性 , 而具有数据本身的属性 。 当某个值插入数据库时, SQLite 将检查它的类型。如果该类型与关联的列不匹配,则 SQLite 会尝试将该值转换成列类型。如果不能转换,则该值将作为其本身具有的类型存储。SQLite 支持 NULL 、INTEGER 、 REAL 、 TEXT 和 BLOB 数据类型。例如:可以在 Integer 字段中存放字符串,或者在布尔型字段中存放浮点数,或者在字符型字段中存放日期型值。但是有一种例外,如果你的主键是 INTEGER ,那么只能存储 6 4位整数 , 当向这种字段中保存除整数以外的数据时, 将会产生错误 。 另外 , SQLite 在解 析REATE TABLE语句时,会忽略 CREATE TABLE 语句中跟在字段名后面的数据类型信息。

SQLite 的特点

SQlite数据库总结起来有五大特点:

1. 零配置

SQlite3不用安装、不用配置、不用启动、关闭或者配置数据库实例。当系统崩溃后不用做任何恢复操作,在下次使用数据库的时候自动恢复。

2. 可移植

它是运行在 Windows 、 Linux 、BSD 、 Mac OS X 和一些商用 Unix 系统, 比如 Sun 的 Solaris 、IBM 的 AIX ,同样,它也可以工作在许多嵌入式操作系统下,比如 Android 、 QNX 、VxWorks、 Palm OS 、 Symbin 和 Windows CE 。

3. 紧凑

SQLite是被设计成轻量级、自包含的。一个头文件、一个 lib 库,你就可以使用关系数据库了,不用任何启动任何系统进程。

4. 简单

SQLite有着简单易用的 API 接口。

5. 可靠

SQLite的源码达到 100% 分支测试覆盖率。

使用SQLiteOpenHelper抽象类建立数据库

抽象类SQLiteOpenHelper用来对数据库进行版本管理,不是必须使用的。

为了实现对数据库版本进行管理, SQLiteOpenHelper 类提供了两个重要的方法 , 分别onCreate(SQLiteDatabasedb) 和 onUpgrade(SQLiteDatabase db, int oldVersion, intnewVersion)用于初次使用软件时生成数据库表,后者用于升级软件时更新数据库表结构。

  1. public SQLiteOpenHelper(Context context,   String name,  
  2. SQLiteDatabase.CursorFactory factory,  int version)  

Context :代表应用的上下文。

Name : 代表数据库的名称。

Factory: 代表记录集游标工厂 , 是专门用来生成记录集游标, 记录集游标是对查询结果进行迭代的,后面我们会继续介绍。

Version :代表数据库的版本,如果以后升级软件的时候,需要更改 Version 版本号,那么onUpgrade(SQLiteDatabase db,int oldVersion, int newVersion) 方法会被调用,在这个方法中比较适合实现软件更新时修改数据库表结构的工作。

实验步骤

1、建立数据库类DatabaseHelper

  1. public class DatabaseHelper extends SQLiteOpenHelper {  
  2.     static String dbName = "myAndroid_db.db";  
  3.     static int version=1;  
  4.    
  5.     public DatabaseHelper(Context context) {  
  6.        super(context, dbName, null, version);     
  7.     }  
  8.     //第一次使用的时候会被调用,用来建库  
  9.     public void onCreate(SQLiteDatabase db) {  
  10.     String sql = "create table person11(personid integer primary key  
  11. autoincrement, name varchar(20),age integer)";  
  12.        db.execSQL(sql);  
  13.     }  
  14.    
  15.     public void onUpgrade(SQLiteDatabase db, int oldVersion,  
  16. int newVersion) {  
  17.        String sql = "drop table if exists person";  
  18.        onCreate(db);  
  19.     }  
  20. }  

2、编写测试类进行测试

  1. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  2. //  String sql = "drop table if exists person";  
  3. //  Log.i("TAG","我被删除了");  
  4. //  onCreate(db);  
  5.         
  6.     String sql = "alter table person add phone char(20) null";  
  7.     db.execSQL(sql);  
  8. }  

3、数据库更新测试

首先修改版本号version的值(递增)

然后重新运行测试方法testCreateDb()

CRUD

实验步骤

建立PersonService业务类

  1. package cn.class3g.service;  
  2. …  
  3. public class PersonService {  
  4.    
  5.     private DatabaseHelper dbHelper;  
  6.     private Context context;  
  7.    
  8.     public PersonService(Context context) {  
  9.        this.context = context;  
  10.        dbHelper = new DatabaseHelper(context);  
  11.     }  
  12.    
  13.     public void save(Person person) {  
  14.        SQLiteDatabase db = dbHelper.getWritableDatabase();  
  15.        // String sql = "insert into person(name,age) values('Tom',21)";  
  16.        // db.execSQL(sql);  
  17.    
  18.        // 防止用户输入数据错误,如:name="T'om"  
  19.        String sql = "insert into person(name,age) values(?,?)";  
  20.        db.execSQL(sql, new Object[] { person.getName(), person.getAge() });  
  21.     }  
  22.    
  23.     public void update(Person person, int id) {  
  24.        SQLiteDatabase db = dbHelper.getWritableDatabase();  
  25.        String sql = "update person set name=?,age=? where personid=?";  
  26.        db.execSQL(sql, new Object[] { person.getName(), person.getAge(), id });  
  27.     }  
  28.    
  29.     public Person find(int id) {  
  30.        SQLiteDatabase db = dbHelper.getReadableDatabase();  
  31.        String sql = "select * from person where personid=?";  
  32.        Cursor cursor = db.rawQuery(sql, new String[] { String.valueOf(id) });  
  33.    
  34.        if (cursor.moveToNext()) {  
  35.            Person person = new Person();  
  36.            person.setName(cursor.getString(cursor.getColumnIndex("name")));  
  37.            person.setId(cursor.getInt(0));  
  38.            person.setAge(cursor.getInt(2));  
  39.    
  40.            cursor.close(); // 关闭游标  
  41.            return person;  
  42.        }  
  43.        return null;  
  44.     }  
  45.    
  46.     public void delete(int id) {  
  47.        SQLiteDatabase db = dbHelper.getReadableDatabase();  
  48.        String sql = "delete from person where personid=?";  
  49.        db.execSQL(sql, new Object[] { id });  
  50.     }  
  51.    
  52.     public List<Person> getScrollData(int startIdx, int count) {  
  53.    
  54.        SQLiteDatabase db = dbHelper.getReadableDatabase();  
  55.        String sql = "select * from person limit ?,?";  
  56.        Cursor cursor = db.rawQuery(sql,  
  57.                      new String[] { String.valueOf(startIdx),  
  58.                                    String.valueOf(count) });  
  59.    
  60.        List<Person> list = new ArrayList<Person>();  
  61.         
  62.        while(cursor.moveToNext()){  
  63.            Person p = new Person();  
  64.            p.setId(cursor.getInt(0));  
  65.            p.setName(cursor.getString(1));  
  66.            p.setAge(cursor.getInt(2));  
  67.             
  68.            list.add(p);  
  69.        }       
  70.        cursor.close();  
  71.        return list;  
  72.     }  
  73.     public long getRecordsCount() {  
  74.        SQLiteDatabase db = dbHelper.getReadableDatabase();  
  75.        String sql = "select count(*) from person";  
  76.        Cursor cursor = db.rawQuery(sql, null);  
  77.        cursor.moveToFirst();  
  78.        long count = cursor.getInt(0);  
  79.        cursor.close();  
  80.        return count;  
  81.     }  
  82. }  

在测试类cn.class3g.db. PersonServiceTest中添加对应测试方法

  1. package cn.class3g.db;  
  2. …  
  3. public class PersonServiceTest extends AndroidTestCase {  
  4.      
  5.     public void testSave() throws Throwable{  
  6.        PersonService service = new PersonService(this.getContext());  
  7.         
  8.        Person person = new Person();  
  9.        person.setName("zhangxiaoxiao");  
  10.        service.save(person);  
  11.         
  12.        Person person2 = new Person();  
  13.        person2.setName("laobi");  
  14.        service.save(person2);  
  15.         
  16.        Person person3 = new Person();  
  17.        person3.setName("lili");  
  18.        service.save(person3);  
  19.         
  20.        Person person4 = new Person();  
  21.        person4.setName("zhaoxiaogang");  
  22.        service.save(person4);       
  23.     }  
  24.     public void testUpdate() throws Throwable{  
  25.        PersonService ps  = new PersonService(this.getContext());  
  26.        Person person = new Person("Ton", 122);  
  27.        ps.update(person, 2);//需要实现查看数据库中Ton的id值  
  28.     }  
  29.     public void testFind() throws Throwable{  
  30.        PersonService ps  = new PersonService(this.getContext());  
  31.        Person person = ps.find(2);  
  32.        Log.i("TAG",person.toString());  
  33.     }    
  34.     public void testDelete() throws Throwable{  
  35.        PersonService ps  = new PersonService(this.getContext());  
  36.        ps.delete(2);      
  37.     }    
  38.     public void testScroll() throws Throwable{  
  39.        PersonService service = new PersonService(this.getContext());  
  40.        List<Person> personList = service.getScrollData(3, 2);  
  41.         
  42.        Log.i("TAG",personList.toString());        
  43.     }    
  44.     public void testCount() throws Throwable{  
  45.        PersonService service = new PersonService(this.getContext());  
  46.        long count = service.getRecordsCount();  
  47.        Log.i("TAG", String.valueOf(count));  
  48.     }  
  49. }  

常见异常

android.database.sqlite.SQLiteException:Can't upgrade read-only database from version 0 to 1: 

这个错误基本上都是sql有问题导致的,仔细检查sql即可。

  • 1
  • 2
  • 下一页

相关内容