天天看點

Android程式中讀取使用已有的SQLite資料庫

方法一:

先在 manifest 裡添權重限:

<span style="font-size:12px;"><uses-permission android:name="android.permission.write_external_storage" />  

<uses-permission android:name="android.permission.mount_unmount_filesystems" /></span>  

第一步先判斷在指定的路勁是否存在,不存在就建立。第二步将android的資源下的資料庫複制到指定路徑下面。第三步就是根據指定路徑打開或者建立資料庫,然後得到操作資料庫的對象,得到操作資料庫的對象了,自然就可以對資料庫中的表進行增删改查等操作了。

<span style="font-size:12px;">sqlitedatabase db;  

    private final string database_path = android.os.environment  

            .getexternalstoragedirectory().getabsolutepath() + "/vote";  

    private string database_filename = "db_vote.db";  

// 初始化資料庫  

    private sqlitedatabase opendatabase() {  

        try {  

            string databasefilename = database_path + "/" + database_filename;  

            file dir = new file(database_path);  

            if (!dir.exists())  

                dir.mkdir();  

            if (!(new file(databasefilename)).exists()) {  

                inputstream is = getresources().openrawresource(r.raw.db_vote);  

                fileoutputstream fos = new fileoutputstream(databasefilename);  

                byte[] buffer = new byte[8192];  

                int count = 0;  

                while ((count = is.read(buffer)) > 0) {  

                    fos.write(buffer, 0, count);  

                }  

                fos.close();  

                is.close();  

            }  

            db = sqlitedatabase.openorcreatedatabase(databasefilename, null);  

            return db;  

        } catch (exception e) {  

            e.printstacktrace();  

        }  

        return null;  

    }</span>  

方法二:

1. 準備sqlite database檔案

   (譯者注:這裡原文是推薦了一個sqlite資料庫管理軟體,這個我覺得可以随自己的喜好,最windows下面有多款可視化的sqlite資料庫管理軟體,可以友善的讀取,編輯資料庫,例如我用的是sqlitestudio

打開資料庫,添加一個新的table “android_metadata",插入一行資料,具體的sql如下:

<span style="font-size:12px;">    create table "android_metadata" ("locale" text default 'en_us')    

    insert into "android_metadata" values ('en_us')  </span>  

(譯者注:上面兩行是表明需要進行的操作,具體可以直接在sqlitesstudio中完成)

    然後你需要對你資料表格的primary id 列重命名為 “_id”,這樣adroid會知道怎麼對id列進行綁定,你可以很容易的在sqlite資料庫管理軟體中進行列編輯。

    這兩步之後,你的sqlite資料庫檔案就準備好了。

  (這裡我保留了id列,即沒有對其進行重命名,測試證明也是沒有問題的)

    現在把你上一步準備好的資料庫檔案放在“assets”檔案夾下面,然後通過繼承 sqliteopenhelper類來建立一個database helper類,

你的databasehelper類大緻可以如下:

<span style="font-size:12px;">public class databasehelper extends sqliteopenhelper{    

    //the android's default system path of your application database.    

    private static string db_path = "/data/data/your_package/databases/";    

    private static string db_name = "mydbname";    

    private sqlitedatabase mydatabase;     

    private final context mycontext;    

    /**  

     * constructor  

     * takes and keeps a reference of the passed context in order to access to the application assets and resources.  

     * @param context  

     */    

    public databasehelper(context context) {    

        super(context, db_name, null, 1);    

        this.mycontext = context;    

    }       

  /**  

     * creates a empty database on the system and rewrites it with your own database.  

     * */    

    public void createdatabase() throws ioexception{    

        boolean dbexist = checkdatabase();    

        if(dbexist){    

            //do nothing - database already exist    

        }else{    

            //by calling this method and empty database will be created into the default system path    

               //of your application so we are gonna be able to overwrite that database with our database.    

            this.getreadabledatabase();    

            try {    

                copydatabase();    

            } catch (ioexception e) {    

                throw new error("error copying database");    

            }    

        }    

    }    

     * check if the database already exist to avoid re-copying the file each time you open the application.  

     * @return true if it exists, false if it doesn't  

    private boolean checkdatabase(){    

        sqlitedatabase checkdb = null;    

        try{    

            string mypath = db_path + db_name;    

            checkdb = sqlitedatabase.opendatabase(mypath, null, sqlitedatabase.open_readonly);    

        }catch(sqliteexception e){    

            //database does't exist yet.    

        if(checkdb != null){    

            checkdb.close();    

        return checkdb != null ? true : false;    

     * copies your database from your local assets-folder to the just created empty database in the  

     * system folder, from where it can be accessed and handled.  

     * this is done by transfering bytestream.  

    private void copydatabase() throws ioexception{    

        //open your local db as the input stream    

        inputstream myinput = mycontext.getassets().open(db_name);    

        // path to the just created empty db    

        string outfilename = db_path + db_name;    

        //open the empty db as the output stream    

        outputstream myoutput = new fileoutputstream(outfilename);    

        //transfer bytes from the inputfile to the outputfile    

        byte[] buffer = new byte[1024];    

        int length;    

        while ((length = myinput.read(buffer))>0){    

            myoutput.write(buffer, 0, length);    

        //close the streams    

        myoutput.flush();    

        myoutput.close();    

        myinput.close();    

    public void opendatabase() throws sqlexception{    

        //open the database    

        string mypath = db_path + db_name;    

        mydatabase = sqlitedatabase.opendatabase(mypath, null, sqlitedatabase.open_readonly);    

    @override    

    public synchronized void close() {    

            if(mydatabase != null)    

                mydatabase.close();    

            super.close();    

    public void oncreate(sqlitedatabase db) {    

    public void onupgrade(sqlitedatabase db, int oldversion, int newversion) {    

        // add your public helper methods to access and get content from the database.    

       // you could return cursors by doing "return mydatabase.query(....)" so it'd be easy    

       // to you to create adapters for your views.    

}  </span>  

就這樣。

    現在你可以建立一個新的databasehelper執行個體,然後調用createdatabase(),然後再調用opendatabase()方法,記住修改db_path字元串中“your_package”為你真正的package名稱(也就是說com.examplename.myapp)

以下是示範代碼:

<span style="font-size:12px;"> ...    

        databasehelper mydbhelper = new databasehelper();    

        mydbhelper = new databasehelper(this);    

        try {    

         mydbhelper.createdatabase();    

     } catch (ioexception ioe) {    

         throw new error("unable to create database");    

     }    

     try {    

         mydbhelper.opendatabase();    

     }catch(sqlexception sqle){    

         throw sqle;    

        ...  </span>  

轉載:http://blog.csdn.net/chaoyu168/article/details/50316885