我们做项目是会遇到需要更新数据库,但是又不想发版本的情况,
这时可以从服务器下载sql文件,然后依次执行
1 ,downLoadFile
File LocalFile = new File(sqlfilepath);
if (LocalFile.exists()) {
InputStreamReader reader = null;
try {
reader = new InputStreamReader(new FileInputStream(LocalFile), "utf-8");
int c;
StringBuffer sb = new StringBuffer();
char buffer[] = new char[1024];
while ((c = reader.read(buffer, 0, 1024)) != -1) {
sb.append(new String(buffer, 0, c));
}
String sqlStr = sb.toString();
sqlStr = sqlStr.replaceAll("\r\n", "");
String[] sqlStrs = sqlStr.split(";");
for (String sql : sqlStrs) {
getDbUtils().execNonQuery(sql);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
3 another
/**
* This reads a file from the given Resource-Id and calls every line of it as a SQL-Statement
*
* @param context
*
* @param resourceId
* e.g. R.raw.food_db
*
* @return Number of SQL-Statements run
* @throws IOException
*/
public int insertFromFile(Context context, int resourceId) throws IOException {
// Reseting Counter
int result = 0;
// Open the resource
InputStream insertsStream = context.getResources().openRawResource(resourceId);
BufferedReader insertReader = new BufferedReader(new InputStreamReader(insertsStream));
// Iterate through lines (assuming each insert has its own line and theres no other stuff)
while (insertReader.ready()) {
String insertStmt = insertReader.readLine();
db.execSQL(insertStmt);
result++;
}
insertReader.close();
// returning number of inserted rows
return result;
}