在开发过程中遇到问题:软件在安装的时候需要给用户安装一个数据库。由于数据较大建议直接将后台生成的数据库或者表直接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语句分成多行显示,就会这条语句执行失败!!! 坑已经踩过 !!!