在開發過程中遇到問題:軟件在安裝的時候需要給用戶安裝一個數據庫。由於數據較大建議直接將後臺生成的數據庫或者表直接copy到本地數據庫中。
要求如上;在網上查找資料的過程中總結出2個方法 :
1、後臺提供 .db 的數據庫文件, 只需要將該文件用文件流的方式拷貝到本地數據庫中、 原理很簡單是根據copy文件的方法進行拷貝即可,使用這種方法你需要提前創建目標數據庫文件。代碼如下: 其中 ServerCfg.DATA_BASE_PATH 是數據庫文件的地址
public static final String DATA_BASE_PATH= "data/data/你的包名/databases";sqliteFileName 是assets下數據庫文件的名字
public static void CopySqliteFileFromRawToDatabases(String sqliteFileName) throws IOException { File dir = new File(ServerCfg.DATA_BASE_PATH); if (!dir.exists() || !dir.isDirectory()) { dir.mkdir(); } File file = new File(dir, sqliteFileName); InputStream inputStream = null; OutputStream outputStream = null; //通過IO流的方式,將assets目錄下的數據庫文件,寫入到SD卡中。 if (!file.exists()) { try { file.createNewFile(); inputStream = ParediseApplication.getContext().getClass().getClassLoader().getResourceAsStream("assets/" + sqliteFileName); outputStream = new FileOutputStream(file); byte[] buffer = new byte[1024]; int len; while ((len = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } } catch (IOException e) { e.printStackTrace(); } finally { if (outputStream != null) { outputStream.flush(); outputStream.close(); } if (inputStream != null) { inputStream.close(); } } } }2、後臺提供的爲 .sql 文件。代碼如下:
private void executeAssetsSQL(SQLiteDatabase db, String schemaName) { BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(context.getAssets() .open(schemaName+".sql"))); String line; String buffer = ""; while ((line = in.readLine()) != null) { buffer += line; if (line.trim().endsWith(";")) { db.execSQL(buffer.replace(";", "")); buffer = ""; } } } catch (IOException e) { e.printStackTrace(); } finally { try { if (in != null) in.close(); } catch (IOException e) { e.printStackTrace(); } } }你需要在一個class 繼承 SQLiteOpenHelper 構造方法中創建數據庫,然後在onCreate 的方法中調用上述方法 同樣的 名字爲assets下對應文件的名字 值得一提的是 studio 支持你查看.sql的文件。你在使用前 需要查看文件中 所有的sql語句是否都在一行 因爲方法是一次讀取一行,然後將其當做sql語句來進行執行,如果你吧一個sql語句分成多行顯示,就會這條語句執行失敗!!! 坑已經踩過 !!!