Android開發之路十二———–SQLite資料庫

來源:互聯網
上載者:User
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)用於初次使用軟體時產生資料庫表,後者用於升級軟體時更新資料庫表結構。

 

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即可。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.