Android使用SQLite資料庫的簡單一實例_Android

來源:互聯網
上載者:User

先畫個圖,瞭解下Android下資料庫操作的簡單流程:

1.首先,寫一個自己的資料庫操作協助類,這個類繼承自Android內建的SQLiteOpenHelper.

2.在自己的DAO層藉助自己的Helper寫資料庫操作的一些方法

3.Activity調用DAO層的資料庫操作方法進行操作

下面例子是:

1.Helper

複製代碼 代碼如下:

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";//資料庫名
 private final static int VERSION = 1;//版本號碼

 //內建的構造方法
 public DBHelper(Context context, String name, CursorFactory factory,
   int version) {
  super(context, name, factory, version);
 }

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

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

 //當資料庫建立的時候調用
 public void onCreate(SQLiteDatabase db) {
  String sql = "create table student(" +
      "id integer primary key autoincrement," +
      "name varchar(20)," +
      "age int)";

  db.execSQL(sql);
 }

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

}

2.寫DAO層

複製代碼 代碼如下:

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

 /**
  * 當Activity中調用此構造方法,傳入一個版本號碼時,系統會在下一次調用資料庫時調用Helper中的onUpgrade()方法進行更新
  * @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 });
 }

 // 其它操作

}

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

另外,資料庫檔案放在這個目錄

相關文章

聯繫我們

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