歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android應用開發之SQLite數據庫

Android應用開發之SQLite數據庫

日期:2017/3/1 10:44:32   编辑:Linux編程

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. public DatabaseHelper(Context context) {
  5. super(context, dbName, null, version);
  6. }
  7. //第一次使用的時候會被調用,用來建庫
  8. public void onCreate(SQLiteDatabase db) {
  9. String sql = "create table person11(personid integer primary key
  10. autoincrement, name varchar(20),age integer)";
  11. db.execSQL(sql);
  12. }
  13. public void onUpgrade(SQLiteDatabase db, int oldVersion,
  14. int newVersion) {
  15. String sql = "drop table if exists person";
  16. onCreate(db);
  17. }
  18. }

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. String sql = "alter table person add phone char(20) null";
  6. db.execSQL(sql);
  7. }

3、數據庫更新測試

首先修改版本號version的值(遞增)

然後重新運行測試方法testCreateDb()

CRUD

實驗步驟

建立PersonService業務類

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

在測試類cn.class3g.db. PersonServiceTest中添加對應測試方法

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

常見異常

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

這個錯誤基本上都是sql有問題導致的,仔細檢查sql即可。

Copyright © Linux教程網 All Rights Reserved