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% 分支测试覆盖率。

SQLiteDatabase 打开文件对应数据库的静态方法:

》StaticSQLiteDatabase openDatabase(File path,SQLiteDatabase.CursorFactory factory , int flags); 打开path文件多代表的SQLite数据库;

》StaticSQLiteDatabase openDatabase(File file,SQLiteDatabase.CursorFactory factory , int flags); 打开或创建(如果不存在) file文件所代笔的SQLite数据库。

》StaticSQLiteDatabase openDatabase(String path,SQLiteDatabase.CursorFactory factory , int flags); 打开或创建(如果不存在) path文件所代笔的SQLite数据库。

二、使用SQLiteOpenHelper抽象类建立数据库

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

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

public SQLiteOpenHelper (Context context, String name,

SQLiteDatabase.CursorFactory factory, int version)

Context :代表应用的上下文。

Name :代表数据库的名称。

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

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

实验步骤

1、建立数据库类DatabaseHelper

public class DatabaseHelper extends SQLiteOpenHelper { static String dbName= "mydb.db"; static int dbVersion = 2; public DatabaseHelper(Context context) { super(context, dbName, null, dbVersion); } //只在初次使用数据库的时候会被自动调用一次 public void onCreate(SQLiteDatabase db) { Log.i("TAG","onCrete被调用了"); String sql = "create table person(personid integer primary key autoincrement," + "name varchar(20), age integer)"; db.execSQL(sql); } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.i("TAG","onUpgrade被调用了"); String sql = "alter table person add phone char(20) null"; db.execSQL(sql); } } 编写测试类进行测试: public class TestDbHelper extends AndroidTestCase { public void testDb() throws Throwable{ DatabaseHelper dbHelper = new DatabaseHelper(this.getContext()); dbHelper.getReadableDatabase(); } }


数据库更新测试

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

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

2、SQLite数据库的crud:

建立PersonService业务类

public class PersonService { private DatabaseHelper dbHelper; private Context context; public PersonService(Context context) { this.context = context; dbHelper = new DatabaseHelper(context); } public void save(Person person) { SQLiteDatabase db = dbHelper.getWritableDatabase(); // String sql = "insert into person(name,age) values('Tom',21)"; // db.execSQL(sql); // 防止用户输入数据错误,如:name="T'om" String sql = "insert into person(name,age) values(?,?)"; db.execSQL(sql, new Object[] { person.getName(), person.getAge() }); } public void update(Person person, int id) { SQLiteDatabase db = dbHelper.getWritableDatabase(); String sql = "update person set name=?,age=? where personid=?"; db.execSQL(sql, new Object[] { person.getName(), person.getAge(), id }); } public Person find(int id) { SQLiteDatabase db = dbHelper.getReadableDatabase(); String sql = "select * from person where personid=?"; Cursor cursor = db.rawQuery(sql, new String[] { String.valueOf(id) }); if (cursor.moveToNext()) { Person person = new Person(); person.setName(cursor.getString(cursor.getColumnIndex("name"))); person.setId(cursor.getInt(0)); person.setAge(cursor.getInt(2)); cursor.close(); // 关闭游标 return person; } return null; } public void delete(int id) { SQLiteDatabase db = dbHelper.getReadableDatabase(); String sql = "delete from person where personid=?"; db.execSQL(sql, new Object[] { id }); } public List<Person> getScrollData(int startIdx, int count) { SQLiteDatabase db = dbHelper.getReadableDatabase(); String sql = "select * from person limit ?,?"; Cursor cursor = db.rawQuery(sql, new String[] { String.valueOf(startIdx), String.valueOf(count) }); List<Person> list = new ArrayList<Person>(); while(cursor.moveToNext()){ Person p = new Person(); p.setId(cursor.getInt(0)); p.setName(cursor.getString(1)); p.setAge(cursor.getInt(2)); list.add(p); } cursor.close(); return list; } public long getRecordsCount() { SQLiteDatabase db = dbHelper.getReadableDatabase(); String sql = "select count(*) from person"; Cursor cursor = db.rawQuery(sql, null); cursor.moveToFirst(); long count = cursor.getInt(0); cursor.close(); return count; } } 在测试类cn.class3g.db. PersonServiceTest中添加对应测试方法 public class PersonServiceTest extends AndroidTestCase { public void testSave() throws Throwable{ PersonService service = new PersonService(this.getContext()); Person person = new Person(); person.setName("zhangxiaoxiao"); service.save(person); Person person2 = new Person(); person2.setName("laobi"); service.save(person2); Person person3 = new Person(); person3.setName("lili"); service.save(person3); Person person4 = new Person(); person4.setName("zhaoxiaogang"); service.save(person4); } public void testUpdate() throws Throwable{ PersonService ps = new PersonService(this.getContext()); Person person = new Person("Ton", 122); ps.update(person, 2);//需要实现查看数据库中Ton的id值 } public void testFind() throws Throwable{ PersonService ps = new PersonService(this.getContext()); Person person = ps.find(2); Log.i("TAG",person.toString()); } public void testDelete() throws Throwable{ PersonService ps = new PersonService(this.getContext()); ps.delete(2); } public void testScroll() throws Throwable{ PersonService service = new PersonService(this.getContext()); List<Person> personList = service.getScrollData(3, 2); Log.i("TAG",personList.toString()); } public void testCount() throws Throwable{ PersonService service = new PersonService(this.getContext()); long count = service.getRecordsCount(); Log.i("TAG", String.valueOf(count)); } }


常见异常

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值