Android应用开发之SQLite数据库
2011-12-28 11:35
357 查看
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)用于初次使用软件时生成数据库表,后者用于升级软件时更新数据库表结构。
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 = "myAndroid_db.db"; static int version=1; public DatabaseHelper(Context context) { super(context, dbName, null, version); } //第一次使用的时候会被调用,用来建库 public void onCreate(SQLiteDatabase db) { String sql = "create table person11(personid integer primary key autoincrement, name varchar(20),age integer)"; db.execSQL(sql); } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { String sql = "drop table if exists person"; onCreate(db); } }
2、编写测试类进行测试
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // String sql = "drop table if exists person"; // Log.i("TAG","我被删除了"); // onCreate(db); String sql = "alter table person add phone char(20) null"; db.execSQL(sql); }
3、数据库更新测试
首先修改版本号version的值(递增)
然后重新运行测试方法testCreateDb()
CRUD
实验步骤建立PersonService业务类
package cn.class3g.service; … 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中添加对应测试方法
package cn.class3g.db; … 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即可。
相关文章推荐
- Android应用之个人应用软件开发(3)【SQLite数据库及理财功能实现】
- 【Android 应用开发】Android 数据存储 之 SQLite数据库详解
- Android开发当中SQLite数据库的应用
- Android应用开发之SQLite数据库2
- Android 开发应用SQLite数据库的简单使用(三)
- Android开发之sqlite数据库的应用
- Android应用开发---SQLiteOpenHelper管理SQLite数据库、ListView
- 【Android 应用开发】Android 数据存储 之 SQLite数据库详解
- 【Android 应用开发】Android 数据存储 之 SQLite数据库详解
- Android开发当中SQLite数据库的应用
- Android应用开发实例篇(2)-----挂接电震动
- Android手机开发:SQLite数据库
- android应用开发全程实录-你有多熟悉listview?(1) 推荐
- 【Android应用开发】 Universal Image Loader ( 使用简介 | 示例代码解析 )
- android开发之提高应用启动速度_splash页面瞬间响应_避免APP启动闪白屏
- Android开发更改应用图标无效的问题
- android应用开发_通过手机QQ分享到空间出现分享错误的无奈原因
- 提升Android应用开发性能的十大要点(1)
- 如何使用Android SDK开发Android应用
- 【转】Android开发数据库三层应用-DataSnap