如下:
private class DatabaseHelper extends SQLiteOpenHelper {
private List tables = new ArrayList();
DatabaseHelper(Context context, String dbName, CursorFactory factory,
int version) {
super(context, dbName, null, version);
}
public void onCreate(SQLiteDatabase db) {
InputStream input = mContext.getResources().openRawResource(
dataScriptId);
BufferedReader reader = null;
try {
logger.error(":::onCreate+DatabaseHelper");
reader = new BufferedReader(new InputStreamReader(input));
executeSqlScript(db, reader);
} catch (IOException e) {
logger.error(":::onCreate+DatabaseHelper:error");
e.printStackTrace();
} finally {
try {
if (input != null) {
input.close();
}
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
for (String table : tables) {
db.execSQL("DROP TABLE IF EXISTS " + table);
}
onCreate(db);
}
public void executeSqlScript(SQLiteDatabase db, BufferedReader reader)
throws IOException {
StringBuilder sql = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
if (TextUtils.isEmpty(line) || line.startsWith("#")) {
continue;
}
if (TextUtils.isEmpty(line) || line.startsWith("=")) {
line = line.replaceAll("=", "");
tables.add(line);
continue;
}
logger.error("###### line : " + line);
line = line.trim();
int index = line.indexOf(';');
if (index >= 0) {
String firstStr = line.substring(0, index + 1);
sql.append(firstStr).append('\n');
try {
db.execSQL(sql.toString()); // make database
} catch (SQLException e) {
e.printStackTrace();
}
sql = new StringBuilder();
if (index < line.length()) {
String lastStr = line.substring(index + 1);
if (!TextUtils.isEmpty(lastStr)) {
sql.append(lastStr);
}
}
} else {
sql.append(line).append('\n');
}
}
if (sql.length() > 0) {
try {
db.execSQL(sql.toString());
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
但是这种做法,sql文件应该如下:
#BEGIN TRANSACTION; ======channel_list====== CREATE TABLE "channel_list" ( "c_id" INTEGER PRIMARY KEY, "c_name" TEXT ); INSERT INTO "channel_list"("c_name") VALUES ("头条"); INSERT INTO "channel_list"("c_name") VALUES ("国内"); INSERT INTO "channel_list"("c_name") VALUES ("国外"); INSERT INTO "channel_list"("c_name") VALUES ("社会"); INSERT INTO "channel_list"("c_name") VALUES ("财经"); CREATE INDEX "IDX_CHANNEL_LIST_ID" ON "channel_list" ("c_id"); ======news_info======= CREATE TABLE "news_info" ( "n_id" INTEGER, "n_cid" INTEGER, "n_title" TEXT, "n_intro" TEXT, "n_publish_time" DATA, "n_source" TEXT, "n_pic_url" TEXT, "n_content" TEXT, "n_create_time" DATA, "flag" INTEGER ); CREATE INDEX "IDX_NEWS_INFO_ID" ON "news_info" ("n_id"); #COMMIT;