將資料庫檔案放到assets下 編寫代碼
/** * 拷貝資料庫 * * @param ctx * @param isNew */public void copyDatabase(Context ctx, boolean isNew) {// 是否初始化資料庫if(isNew){ // 檢查 SQLite 資料庫檔案是否存在 if ((new File(DB_PATH + DB_NAME)).exists() == false) { // 如 SQLite 資料庫檔案不存在,再檢查一下 database 目錄是否存在 File f = new File(DB_PATH); // 如 database 目錄不存在,建立該目錄 if (!f.exists()) { f.mkdir(); } try { // 得到 assets 目錄下我們實現準備好的 SQLite 資料庫作為輸入資料流 InputStream is = ctx.getAssets().open(DB_NAME); // 輸出資料流 OutputStream os = new FileOutputStream(DB_PATH + DB_NAME); // 檔案寫入 byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { os.write(buffer, 0, length); } // 關閉檔案流 os.flush(); os.close(); is.close(); } catch (Exception e) { e.printStackTrace(); } }}}
兩個重要的變數:
// 資料庫路徑final static String DB_PATH = "/data/data/com.example.test/database/";// 資料庫名稱final static String DB_NAME = "ywyd.sqlite";
測試是否成功:
public void testData(){// 下面測試 /data/data/com.test.db/databases/ 下的資料庫是否能正常工作 SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(DB_PATH + DB_NAME, null); Cursor cursor = database.rawQuery("select * from sys_config", null); if (cursor.getCount() > 0) { cursor.moveToFirst();String strtest = cursor.getString(3);// 看輸出的資訊是否正確System.out.println(strtest); } cursor.close();}
在Activity中調用:
SqlLiteHelper helper = new SqlLiteHelper();helper.copyDatabase(this.getBaseContext(), true);//helper.testData();
原文地址 http://blog.csdn.net/yueritian/article/details/46471669