N年不開張了,寫一個關於Android中用檔案初始化sqlite 資料庫的文章

來源:互聯網
上載者:User

最近開始學習安卓編程,自己寫一個小項目。有個需求是從一個檔案中初始化一個sqlite資料庫。就是我有一個含有很多SQL語句的檔案,我希望我的安卓程式第一次啟動時,執行這個sql,初始化資料庫,但在以後的執行中,不在執行這個sql,可以說是一個非常典型的引用。

google了一下,有關這項任務的實現的是是這篇文章“:Using your own SQLite database in Android applications:http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/。

我試了他的方法,可以用,但有兩點讓我很不爽:

1)它的資料庫初始化不是用sql語句,而是用一個現成的sqlite的二進位檔案進行直接copy到Android系統的資料庫路徑中。我一方面不太放心這種二進位檔案的直接copy,另一方面,如果sqlite資料庫的二進位結構有所升級或變動,我的程式就無法對所有sqlite版本相容了。

2)DataBaseHelper 類雖然是extends SQLiteOpenHelper,但它完全沒有按照原來SQLiteOpenHelper類原先的使用邏輯,沒有重載onCreate和onOpen之類,自己去寫了檢測資料庫是否存在,開啟和關閉資料庫等函數。使得這個類擴充SQLiteOpenHelper幾乎沒有意義,差不多是重建了應用邏輯,讓我用不了SQLiteOpenHelper。getReadableDatabase等函數,很不爽(也許是本人的潔癖)。

經過調試,發現SQLiteOpenHelper的onCreate僅在程式第一次使用資料庫時執行,然後執行onCreate;此後的執行就會跳過onCreate,直接執行onOpen。因此完全無需自己去檢測資料庫是否最在。一下按照SQLiteOpenHelper的”正確“使用方法,本人寫的SQLiteOpenHelper的子類,你可以用它初始你的Android資料庫。資料庫用sql語句形式,放在項目的res/raw目錄底下,記住每行一條語句(因為我用readline()來讀源檔案),不能換行!你可以用本機資料庫匯出工具,我用的是firefox
extension: SQLite manager。

/**
 *
 */
package com.yourpackage;

import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * @author li youhua
 *
 */
public class FileSQLiteHelp extends SQLiteOpenHelper {
    private static String DB_PATH = "/data/data/your_package_name/databases/";
    private static final String DB_NAME = "your_db_name.db";

    private SQLiteDatabase myDataBase;

    private final Context myContext;

    public FileSQLiteHelp(Context context) {
        super(context, DB_NAME, null, 1);
        this.myContext = context;
    }

    /**
     * inital your database from your local res-raw-folder to the just created
     * empty database in the system folder, from where it can be accessed and
     * handled.
     * */
    private void initDataBase() throws IOException {

        // Open your local db as the input stream
        // InputStream myInput = myContext.getAssets().open(DB_NAME);
        InputStream myInput = myContext.getResources().openRawResource(
                R.raw.your_db_file_name);
        InputStreamReader reader = new InputStreamReader(myInput);
        BufferedReader breader = new BufferedReader(reader);

        // Path to the just created empty db
        String outFileName = DB_PATH + DB_NAME, str;

        // Open the empty db as the output stream
        FileWriter myOutput = new FileWriter(outFileName, true);

        while ((str = breader.readLine()) != null) {
            myDataBase.execSQL(str); //exec your SQL line by line.
        }

        // Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();

    }

    /*
     * (non-Javadoc)
     *
     * @see
     * android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite
     * .SQLiteDatabase)
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        myDataBase = db;

            try {
                this.initDataBase();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        
    }
    
    @Override
    public void onOpen (SQLiteDatabase db){
        boolean readOnly=db.isReadOnly();
        
    }
    /*
     * (non-Javadoc)
     *
     * @see
     * android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite
     * .SQLiteDatabase, int, int)
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

    }
}

其實代碼非常少,就這麼點夠了。這樣你就可以按正常邏輯用SQLiteOpenHelper.getReadableDatabase()來使用你的資料庫了。

聯繫我們

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