Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android開發系列(九):創建數據庫以及完成簡單的CRUD操作

Android開發系列(九):創建數據庫以及完成簡單的CRUD操作

編輯:關於Android編程

本篇博文主要實現簡單的創建數據庫以及實現CRUD操作。

首先,我們建立一個Android Project,命名為db


一、完成數據庫的創建操作:

用SQLiteOpenHelper類中的getWritableDatabase()和getReadableDatabase()都可以獲取一個操作數據庫的SQLiteDatabase實例,其中getReadableDatabase()方法中會調用getWritableDatabase()方法。

區別:其中,getWritableDatabase() 方法以讀寫方式打開數據庫,一旦數據庫的磁盤空間滿了,數據庫就只能讀而不能寫,倘若使用的是getWritableDatabase() 方法就會出錯。getReadableDatabase()方法則是先以讀寫方式打開數據庫,如果數據庫的磁盤空間滿了,就會打開失敗,當打開失敗後會繼續嘗試以只讀方式打開數據庫;如果此時數據庫空間出現了空余,則會成功獲取一個操作數據庫的SQLiteDatabase對象。

我們首先建立一個類(繼承SQLiteOpenHelper)DBOpenHelper.java:

package cn.itcast.service;

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

public class DBOpenHelper extends SQLiteOpenHelper {

	//構造函數,調用父類的SQLiteOpenHelper的構造函數
	public DBOpenHelper(Context context) {
		super(context, "itcast.db", null, 1);
		//<包>/databases/
	}

	@Override
	public void onCreate(SQLiteDatabase db) {//是在數據庫每一次被創建的時候調用的
		db.execSQL("CREATE TABLE person(personid integer primary key autoincrement, name varchar(20), phone VARCHAR(12) NULL)");
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {//在數據庫的版本發生變化時會被調用
		db.execSQL("ALTER TABLE person ADD amount integer");
	}

}

onCreate()方法在初次生成數據庫時才會被調用,在onCreate()方法裡可以生成數據庫表結構及添加一些應用使用到的初始化數據。

onUpgrade()方法在數據庫的版本發生變化時會被調用,一般在軟件升級時才需改變版本號,而數據庫的版本是由程序員控制的。


然後,我們建立一個測試類,來實現調用DBOpenHelper中的方法來創建數據庫DBTest.java:

package cn.itcast.test;
public class DBTest extends AndroidTestCase {
   public void testCreateDB() throws Exception{
		DBOpenHelper dbOpenHelper = new DBOpenHelper(getContext());
		dbOpenHelper.getWritableDatabase();
	}
}
關於測試需要在AndroidManifest.xml中配置幾條語句,這點不要忘了。

運行測試發現在File Explorer視圖中的/data/data/cn.itcast.db/databases目錄下有個itcast.db的文件,就是我們創建的數據庫了。

二、完成增刪改查CRUD操作:

我們用Person來做例子

首先,用建立一個javabean:Person.java

package cn.itcast.domain;

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

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

	public void setAmount(Integer amount) {
		this.amount = amount;
	}

	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;
	}
	@Override
	public String toString() {
		return "Person [id=" + id + ", name=" + name + ", phone=" + phone
				+ ", amount=" + amount + "]";
	}


	
}
然後,我們需要編寫業務層的類,PersonService.java

package cn.itcast.service;

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

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

import cn.itcast.domain.Person;

public class PersonService {
	private DBOpenHelper dbOpenHelper;

	
	public PersonService(Context context) {
		this.dbOpenHelper = new DBOpenHelper(context);
	}

	/**
	 * 添加記錄
	 * @param person
	 */
	public void save(Person person){
		SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
		db.execSQL("insert into person(name, phone, amount) values(?,?,?)",
				new Object[]{person.getName(), person.getPhone(), person.getAmount()});
	}
	/**
	 * 刪除記錄
	 * @param id 記錄ID
	 */
	public void delete(Integer id){
		SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
		db.execSQL("delete from person where personid=?", new Object[]{id});
	}
	/**
	 * 更新記錄
	 * @param person
	 */
	public void update(Person person){
		SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
		db.execSQL("update person set name=?,phone=?,amount=? where personid=?",
				new Object[]{person.getName(), person.getPhone(),  person.getAmount(), person.getId()});
	}
	/**
	 * 查詢記錄
	 * @param id 記錄ID
	 * @return
	 */
	public Person find(Integer id){
		SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
		Cursor cursor = db.rawQuery("select * from person where personid=?", new String[]{id.toString()});
		if(cursor.moveToFirst()){
			int personid = cursor.getInt(cursor.getColumnIndex("personid"));
			int amount = cursor.getInt(cursor.getColumnIndex("amount"));
			String name = cursor.getString(cursor.getColumnIndex("name"));
			String phone = cursor.getString(cursor.getColumnIndex("phone"));
			return new Person(personid, name, phone, amount);
		}
		cursor.close();
		return null;
	}
	/**
	 * 分頁獲取記錄
	 * @param offset 跳過前面多少條記錄
	 * @param maxResult 每頁獲取多少條記錄
	 * @return
	 */
	public List getScrollData(int offset, int maxResult){
		List persons = new ArrayList();
		SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
		Cursor cursor = db.rawQuery("select * from person order by personid asc limit ?,?",
				new String[]{String.valueOf(offset), String.valueOf(maxResult)});
		while(cursor.moveToNext()){
			int personid = cursor.getInt(cursor.getColumnIndex("personid"));
			int amount = cursor.getInt(cursor.getColumnIndex("amount"));
			String name = cursor.getString(cursor.getColumnIndex("name"));
			String phone = cursor.getString(cursor.getColumnIndex("phone"));
			persons.add(new Person(personid, name, phone, amount));
		}
		cursor.close();
		return persons;
	}
	/**
	 * 分頁獲取記錄
	 * @param offset 跳過前面多少條記錄
	 * @param maxResult 每頁獲取多少條記錄
	 * @return
	 */
	public Cursor getCursorScrollData(int offset, int maxResult){
		SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
		Cursor cursor = db.rawQuery("select personid as _id,name,phone,amount from person order by personid asc limit ?,?",
				new String[]{String.valueOf(offset), String.valueOf(maxResult)});
		return cursor;
	}
	
	/**
	 * 獲取記錄總數
	 * @return
	 */
	public long getCount(){
		SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
		Cursor cursor = db.rawQuery("select count(*) from person", null);
		cursor.moveToFirst();
		long result = cursor.getLong(0);
		cursor.close();
		return result;
	}
}
然後,我們就需要執行測試了PersonServiceTest.java:

package cn.itcast.test;

import java.util.List;

import cn.itcast.domain.Person;
import cn.itcast.service.DBOpenHelper;
import cn.itcast.service.PersonService;
import android.test.AndroidTestCase;
import android.util.Log;

public class PersonServiceTest extends AndroidTestCase {
	private static final String TAG = "PersonServiceTest";
	
	public void testCreateDB() throws Exception{
		DBOpenHelper dbOpenHelper = new DBOpenHelper(getContext());
		dbOpenHelper.getWritableDatabase();
	}
	
	public void testSave() throws Exception{
		PersonService service = new PersonService(this.getContext());
		for(int i = 0 ; i < 20 ; i++){
			Person person = new Person("zhangxx"+ i, "136765765"+ i, 100);
			service.save(person);
		}
	}
	
	public void testDelete() throws Exception{
		PersonService service = new PersonService(this.getContext());
		service.delete(21);
	}
	
	public void testUpdate() throws Exception{
		PersonService service = new PersonService(this.getContext());
		Person person = service.find(1);
		person.setName("zhangxiaoxiao");
		service.update(person);
	}
	
	public void testFind() throws Exception{
		PersonService service = new PersonService(this.getContext());
		Person person = service.find(1);
		Log.i(TAG, person.toString());
	}
	
	public void testScrollData() throws Exception{
		PersonService service = new PersonService(this.getContext());
		List persons = service.getScrollData(0, 5);
		for(Person person : persons){
			Log.i(TAG, person.toString());
		}
	}
	
	public void testCount() throws Exception{
		PersonService service = new PersonService(this.getContext());
		long result = service.getCount();
		Log.i(TAG, result+"");
	}

	public void testUpdateAmount() throws Exception{
		PersonService service = new PersonService(this.getContext());
		Person person1 = service.find(1);
		Person person2 = service.find(2);
		person1.setAmount(100);
		person2.setAmount(50);
		service.update(person1);
		service.update(person2);
		
	}
}
可以在找到itcast.db之後,通過下載:SQLite Explorer來打開查看








  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved