Android SQLite資料庫增刪改查操作的案例分析

來源:互聯網
上載者:User

Person實體類

複製代碼 代碼如下:package com.ljq.domain;

public class Person {
private Integer id;
private String name;
private String phone;

public Person() {
super();
}

public Person(String name, String phone) {
super();
this.name = name;
this.phone = phone;
}

public Person(Integer id, String name, String phone) {
super();
this.id = id;
this.name = name;
this.phone = phone;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getPhone() {
return phone;
}

public void setPhone(String phone) {
this.phone = phone;
}

}

DBOpenHelper資料庫關聯類別
複製代碼 代碼如下:package com.ljq.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBOpenHelper extends SQLiteOpenHelper {
// 類沒有執行個體化,是不能用作父類構造器的參數,必須聲明為靜態
private static final String DBNAME = "ljq.db";
private static final int VERSION = 1;

// 第三個參數CursorFactory指定在執行查詢時獲得一個遊標執行個體的工廠類,
// 設定為null,代表使用系統預設的工廠類
public DBOpenHelper(Context context) {
super(context, DBNAME, null, VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE PERSON (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME VARCHAR(20), PHONE VARCHAR(20))");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// 註:生產環境上不能做刪除操作
db.execSQL("DROP TABLE IF EXISTS PERSON");
onCreate(db);
}
}

PersonService業務類
複製代碼 代碼如下:package com.ljq.db;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;

import com.ljq.domain.Person;

public class PersonService {
private DBOpenHelper dbOpenHelper = null;

/**
* 建構函式
*
* 調用getWritableDatabase()或getReadableDatabase()方法後,會緩衝SQLiteDatabase執行個體;
* 因為這裡是手機應用程式,一般只有一個使用者訪問資料庫,所以建議不關閉資料庫,保持串連狀態。
* getWritableDatabase(),getReadableDatabase的區別是當資料庫寫滿時,調用前者會報錯,調用後者不會,
* 所以如果不是更新資料庫的話,最好調用後者來獲得資料庫連接。
*
* 對於熟悉SQL語句的程式員最好使用exeSQL(),rawQuery(),因為比較直觀明了
*
* @param context
*/
public PersonService(Context context){
dbOpenHelper = new DBOpenHelper(context);
}

public void save(Person person){
dbOpenHelper.getWritableDatabase().execSQL("insert into person(name, phone) values (?, ?)",
new Object[]{person.getName(), person.getPhone()});
}

public void update(Person person){
dbOpenHelper.getWritableDatabase().execSQL("update person set name=?, phone=? where id=?",
new Object[]{person.getName(), person.getPhone(), person.getId()});
}

public void delete(Integer... ids){
if(ids.length>0){
StringBuffer sb = new StringBuffer();
for(Integer id : ids){
sb.append("?").append(",");
}
sb.deleteCharAt(sb.length() - 1);
dbOpenHelper.getWritableDatabase().execSQL("delete from person where id in ("+sb+")", (Object[])ids);
}
}

public Person find(Integer id){
Cursor cursor = dbOpenHelper.getReadableDatabase().rawQuery("select id, name, phone from person where id=?",
new String[]{String.valueOf(id)});
if(cursor.moveToNext()){
int personid = cursor.getInt(0);
String name = cursor.getString(1);
String phone = cursor.getString(2);
return new Person(personid, name, phone);
}
return null;
}

public long getCount(){
Cursor cursor = dbOpenHelper.getReadableDatabase().query("person",
new String[]{"count(*)"}, null,null,null,null,null);
if(cursor.moveToNext()){
return cursor.getLong(0);
}
return 0;
}

/**
* 分頁
*
* @param startResult 位移量,預設從0開始
* @param maxResult 每頁顯示的條數
* @return
*/
public List<Person> getScrollData(int startResult, int maxResult){
List<Person> persons = new ArrayList<Person>();
//Cursor cursor = dbOpenHelper.getReadableDatabase().query("person", new String[]{"id, name, phone"},
// "name like ?", new String[]{"%ljq%"}, null, null, "id desc", "1,2");
Cursor cursor = dbOpenHelper.getReadableDatabase().rawQuery("select * from person limit ?,?",
new String[]{String.valueOf(startResult), String.valueOf(maxResult)});
while(cursor.moveToNext()) {
int personid = cursor.getInt(0);
String name = cursor.getString(1);
String phone = cursor.getString(2);
persons.add(new Person(personid, name, phone));
}
return persons;
}

}

PersonServiceTest測試類別
複製代碼 代碼如下:package com.ljq.test;

import java.util.List;

import com.ljq.db.PersonService;
import com.ljq.domain.Person;

import android.test.AndroidTestCase;
import android.util.Log;

public class PersonServiceTest extends AndroidTestCase{
private final String TAG = "PersonServiceTest";

public void testSave() throws Exception{
PersonService personService = new PersonService(this.getContext());
personService.save(new Person("zhangsan1", "059188893343"));
personService.save(new Person("zhangsan2", "059188893343"));
personService.save(new Person("zhangsan3", "059188893343"));
personService.save(new Person("zhangsan4", "059188893343"));
personService.save(new Person("zhangsan5", "059188893343"));
}

public void testUpdate() throws Exception{
PersonService personService = new PersonService(this.getContext());
Person person = personService.find(1);
person.setName("linjiqin");
personService.update(person);
}

public void testFind() throws Exception{
PersonService personService = new PersonService(this.getContext());
Person person = personService.find(1);
Log.i(TAG, person.getName());
}

public void testList() throws Exception{
PersonService personService = new PersonService(this.getContext());
List<Person> persons = personService.getScrollData(0, 10);
for(Person person : persons){
Log.i(TAG, person.getId() + " : " + person.getName());
}
}

public void testCount() throws Exception{
PersonService personService = new PersonService(this.getContext());
Log.i(TAG, String.valueOf(personService.getCount()));
}

public void testDelete() throws Exception{
PersonService personService = new PersonService(this.getContext());
personService.delete(1);
}

public void testDeleteMore() throws Exception{
PersonService personService = new PersonService(this.getContext());
personService.delete(new Integer[]{2, 5, 6});
}
}

運行結果

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.