歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android數據處理---SQLite

Android數據處理---SQLite

日期:2017/3/1 10:46:29   编辑: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% 分支測試覆蓋率。

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));

}

}

Copyright © Linux教程網 All Rights Reserved