欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android使用SQLite數(shù)據(jù)庫的簡單實(shí)例

 更新時(shí)間:2013年12月10日 15:45:57   作者:  
這篇文章主要介紹了Android使用SQLite數(shù)據(jù)庫的簡單實(shí)例,有需要的朋友可以參考一下

先畫個(gè)圖,了解下Android下數(shù)據(jù)庫操作的簡單流程:

1.首先,寫一個(gè)自己的數(shù)據(jù)庫操作幫助類,這個(gè)類繼承自Android自帶的SQLiteOpenHelper.

2.在自己的DAO層借助自己的Helper寫數(shù)據(jù)庫操作的一些方法

3.Activity調(diào)用DAO層的數(shù)據(jù)庫操作方法進(jìn)行操作

下面例子是:

1.Helper

復(fù)制代碼 代碼如下:

package cn.learn.db.util;

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

public class DBHelper extends SQLiteOpenHelper {

 private final static String DB_NAME ="test.db";//數(shù)據(jù)庫名
 private final static int VERSION = 1;//版本號

 //自帶的構(gòu)造方法
 public DBHelper(Context context, String name, CursorFactory factory,
   int version) {
  super(context, name, factory, version);
 }

 //為了每次構(gòu)造時(shí)不用傳入dbName和版本號,自己得新定義一個(gè)構(gòu)造方法
 public DBHelper(Context cxt){
  this(cxt, DB_NAME, null, VERSION);//調(diào)用上面的構(gòu)造方法
 }

 //版本變更時(shí)
 public DBHelper(Context cxt,int version) {
  this(cxt,DB_NAME,null,version);
 }

 //當(dāng)數(shù)據(jù)庫創(chuàng)建的時(shí)候調(diào)用
 public void onCreate(SQLiteDatabase db) {
  String sql = "create table student(" +
      "id integer primary key autoincrement," +
      "name varchar(20)," +
      "age int)";

  db.execSQL(sql);
 }

 //版本更新時(shí)調(diào)用
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  String sql  = "update student ....";//自己的Update操作
  db.execSQL(sql);
 }

}

2.寫DAO層

復(fù)制代碼 代碼如下:

package cn.learn.db.dao;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import cn.learn.db.dao.domain.Student;
import cn.learn.db.util.DBHelper;

public class StudentDao {

 DBHelper helper = null;

 public StudentDao(Context cxt) {
  helper = new DBHelper(cxt);
 }

 /**
  * 當(dāng)Activity中調(diào)用此構(gòu)造方法,傳入一個(gè)版本號時(shí),系統(tǒng)會在下一次調(diào)用數(shù)據(jù)庫時(shí)調(diào)用Helper中的onUpgrade()方法進(jìn)行更新
  * @param cxt
  * @param version
  */
 public StudentDao(Context cxt, int version) {
  helper = new DBHelper(cxt, version);
 }

 // 插入操作
 public void insertData(Student stu) {
  String sql = "insert into student (name,age)values(?,?)";
  SQLiteDatabase db = helper.getWritableDatabase();
  db.execSQL(sql, new Object[] { stu.name, stu.age });
 }

 // 其它操作

}

完成這些,其它操作就簡單了....

另外,數(shù)據(jù)庫文件放在這個(gè)目錄

相關(guān)文章

最新評論