Android如何使用SQLiteOpenHelper

來源:互聯網
上載者:User

 1.SQLiteOpenHelper

  SQliteOpenHelper是一個抽象類別,來管理資料庫的建立和版本的管理。要使用它必須實現它的nCreate(SQLiteDatabase),onUpgrade(SQLiteDatabase, int, int)方法

  onCreate:當資料庫第一次被建立的時候被執行,例如建立表,初始化資料等。

  onUpgrade:當資料庫需要被更新的時候執行,例如刪除久表,建立新表。

  2.實現代碼

package xqh.utils;

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 static final int VERSION = 1;
    //建立一個表
    String sql = "create table if not exists TestUsers"+
    "(id int primary key,name varchar,sex varchar)";
   
    public DBHelper(Context context, String name, CursorFactory factory,
            int version) {
        super(context, name, factory, version);
    }

    public DBHelper(Context context,String name,int version){
        this(context,name,null,version);
    }
   
    public DBHelper(Context context,String name){
        this(context,name,VERSION);
    }
   
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
       
    }
   
}

 

  3.SQLite的使用

  Android提供了一個名為SQLiteDatabase的類,它封裝了一些操作資料庫的API。使用它能實現基本的CRUD操作,通過getWritableDatabase()和getReadableDatabase()可以擷取資料庫執行個體。

  4.實現代碼

package xqh.sqlite;

import xqh.utils.DBHelper;
import android.app.Activity;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.Button;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;;

public class TestSQLite extends Activity {

    Button textBtn = null;
    Button btnCreateDb = null;
    Button btnCreateTb = null;
    Button btnInsert = null;
    Button btnUpdate = null;
    Button btnDelete = null;
    DBHelper dbHelper = null;
    SQLiteDatabase db = null;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sqlitetest);
       
        OpenDb();
       
        textBtn = (Button)findViewById(R.id.btnHeader);
        textBtn.setFocusable(true);
       
//        btnCreateDb = (Button)findViewById(R.id.btnCreateDb);
//        btnCreateDb.setOnClickListener(createDbListener);
//       
//        btnCreateTb = (Button)findViewById(R.id.btnCreateTb);
//        btnCreateTb.setOnClickListener(createTbListener);
       
        btnInsert = (Button)findViewById(R.id.btnInsert);
        btnInsert.setOnClickListener(insertTbListener);
       
        btnUpdate = (Button)findViewById(R.id.btnUpdate);
        btnUpdate.setOnClickListener(updateTbListener);
       
        btnDelete = (Button)findViewById(R.id.btnDelete);
        btnDelete.setOnClickListener(deleteTbListener);

    }
   
    public OnClickListener deleteTbListener = new OnClickListener() {
        public void onClick(View v) {
            DeleteTb();
        }
    };
   
    public OnClickListener updateTbListener = new OnClickListener() {
        public void onClick(View v) {
            UpdateTb();
        }
    };
   
    public OnClickListener insertTbListener = new OnClickListener() {
        public void onClick(View v) {
            InsertTb();
        }
    };
   
//    public OnClickListener createDbListener = new OnClickListener() {
//        public void onClick(View v) {
//            CreateDatabase("TestDb01");
//        }
//    };

//    public OnClickListener createTbListener = new OnClickListener() {
//        public void onClick(View v) {
//            CreateTable();
//        }
//    };
   
//    /**
//     * 建立一個資料庫
//     * @param dbName
//     * @return
//     */
//    public SQLiteDatabase CreateDatabase(String dbName){
//        dbHelper = new DBHelper(this, dbName);
//        return dbHelper.getWritableDatabase();
//    }
   
    /**
     * 建立一個表
     * @param db
     */
    public void CreateTable(){
        db = dbHelper.getWritableDatabase();
        String sql = "create table if not exists TestUsers"+
                        "(id int primary key,name varchar,sex varchar)";
        try {
            db.execSQL(sql);
        } catch (SQLException e) {
            Log.i("err", "create table failed");
        }
    }
   
    /**
     * 插入資料 www.2cto.com
     */
    public void InsertTb(){
        db = dbHelper.getWritableDatabase();
        String sql = "insert into TestUsers (id,name,sex) values (2,'hongguang','men')";
        try {
            db.execSQL(sql);
        } catch (SQLException e) {
            Log.i("err", "insert failed");
        }
    }
   
    /**
     * 更新資料
     */
    public void UpdateTb() {
        db = dbHelper.getWritableDatabase();
        String sql = "Update TestUsers set name = 'anhong',sex = 'men' where id = 2";
        try {
            db.execSQL(sql);
        } catch (SQLException e) {
            Log.i("err", "update failed");
        }
    }
   
    /**
     * 刪除資料
     */
    public void DeleteTb(){
        db = dbHelper.getWritableDatabase();
        String sql = "delete from TestUsers where id = 2";
        try {
            db.execSQL(sql);
        } catch (SQLException e) {
            Log.i("err", "delete failed");
        }
    }
   
    /**
     * 開啟資料庫
     */
    public void OpenDb(){
        dbHelper = new DBHelper(this, "TestDb01");
        db = dbHelper.getWritableDatabase();
    }
   
    /**
     * 關閉資料庫
     */
    public void CloseDb(){
        dbHelper.close();
    }
   
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(db!=null){
            db.close();
        }
        if(dbHelper!=null){
            dbHelper.close();
        }
    }
   
}

 

  5.一些SQLite操作命令

  5.1 adb shell 進入命令模式

  5.2 cd 檔案名稱 進入檔案

  5.3 ls或ls -l 查看目錄下的檔案

  5.4 sqlite3 資料庫名 進入資料庫

  5.5 .schema 查看資料庫下的資訊

  5.6 ctrl+d 退出sqlite模式

  6.測試

 

 

SQLiteDatabase是Android SDK中操作資料庫的核心類之一。使用SQLiteDatabase可以開啟資料庫,也可以對資料庫進行操作。然而為了資料庫升級的需要以及使用更方便,往往使用SQLiteOpenHelper的子類來完成建立、開啟資料庫及各種資料庫操作。
     SQLiteOpenHelper是個抽象類別,在該類中有如下兩個抽象方法,SQLiteOpenHelper的子類必須實現這兩個方法。
     public abstract void onCreate(SQLiteDatabase db);
     public abstract void onUpdate(SQLiteDatabase db,int oldVersion,int newVersion);
     SQLiteOpenHelper會自動檢測資料庫檔案是否存在。如果存在,會開啟這個資料庫,在這種情況下就不會調用onCreate()方法。如果資料庫檔案不存在,SQLiteOpenHelper首先會建立一個資料庫檔案,然後開啟這個資料庫,最後調用onCreate()方法。因此,onCreate()方法一般用來在新建立的資料庫中建立表、視圖等資料庫組建。也就是說oncreate()方法在資料庫檔案第一次建立時調用。
    先看看SQLiteOpenHelper類的構造方法再解釋onUpdate()方法何時會被調用。
    public SQLiteOpenHelper(Context context,String name,CursorFactory factory,int version);
    其中name參數表示資料庫檔案名(不包括檔案路徑),SQLiteOpenHelper會根據這個檔案名稱建立資料庫檔案。version表示資料庫的版本號碼。如果當前傳入的資料庫版本號碼比上次建立或升級的版本號碼高,SQLiteOpenHelper就會調用onUpdate()方法。也就是說,當資料庫第一次建立時會有一個初始的版本號碼。當需要對資料庫中的表、視圖等組建升級時可以增大版本號碼,再重新建立它們。現在總結一下oncreate()和onUpdate()調用過程。
    1.如果資料庫檔案不存在,SQLiteOpenHelper在自動建立資料庫後會調用oncreate()方法,在該方法中一般需要建立表、視圖等組件。在建立前資料庫一般是空的,因此不需要先刪除資料庫中相關的組件。
    2.如果資料庫檔案存在,並且目前的版本號高於上次建立或升級的版本號碼,SQLiteOpenHelper會調用onUpdate()方法,調用該方法後會更新資料庫的版本號碼。在onupdate()方法中除了建立表、視圖等組件外,還需要先刪除這些相關的組件,因此,在調用onupdate()方法前,資料庫是存在的,裡面還原許多資料庫組建。
     綜合上述兩點,可以得出一個結論。如果資料庫檔案不存在,只有oncreate()被調用(該方法在建立資料庫時被調用一次)。如果資料庫檔案存在,會調用onupdate()方法升級資料庫,並更新版本號碼。

 
摘自 wangjia55的專欄

聯繫我們

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