標籤:
當我們在使用SQLiteOpenHelper時,經常使用db.execSQL(String sql)方法寫入對應語句實現建立表的操作,這樣的確可以實現商務邏輯。與此同時還有一種更靈活的方法,從assets檔案夾下讀取對應的.sql檔案,然後建立表。
1.首先在工程的assets檔案夾下,添加對應的.sql檔案
2.配置一個Configuration類,用於儲存固定路徑變數
[java] view plaincopy
- public class Configuration {
- public static final String DB_PATH = "schema";
- public static final String DB_NAME = "test.db";
- public static final int DB_VERSION = 1;
- public static int oldVersion = -1;
-
- }
3.邏輯實作類別,executeAssetsSQL方法用於向Assets檔案夾對應的路徑讀取SQL語句然後執行建立操作
[java] view plaincopy
- public class DBHelper extends SQLiteOpenHelper {
-
- private Context mContext;
-
- public DBHelper(Context context, String databaseName,
- CursorFactory factory, int version) {
- super(context, databaseName, factory, version);
- mContext = context;
- }
-
- /**
- * 資料庫第一次建立時調用
- * */
- @Override
- public void onCreate(SQLiteDatabase db) {
- executeAssetsSQL(db, "schema.sql");
- System.out.println("建立表");
- }
-
- /**
- * 資料庫升級時調用
- * */
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
- //資料庫不升級
- if (newVersion <= oldVersion) {
- return;
- }
- Configuration.oldVersion = oldVersion;
-
- int changeCnt = newVersion - oldVersion;
- for (int i = 0; i < changeCnt; i++) {
- // 依次執行updatei_i+1檔案 由1更新到2 [1-2],2更新到3 [2-3]
- String schemaName = "update" + (oldVersion + i) + "_"
- + (oldVersion + i + 1) + ".sql";
- executeAssetsSQL(db, schemaName);
- }
- }
-
- /**
- * 讀取資料庫檔案(.sql),並執行sql語句
- * */
- private void executeAssetsSQL(SQLiteDatabase db, String schemaName) {
- BufferedReader in = null;
- try {
- in = new BufferedReader(new InputStreamReader(mContext.getAssets()
- .open(Configuration.DB_PATH + "/" + schemaName)));
-
- System.out.println("路徑:"+Configuration.DB_PATH + "/" + schemaName);
- String line;
- String buffer = "";
- while ((line = in.readLine()) != null) {
- buffer += line;
- if (line.trim().endsWith(";")) {
- db.execSQL(buffer.replace(";", ""));
- buffer = "";
- }
- }
- } catch (IOException e) {
- Log.e("db-error", e.toString());
- } finally {
- try {
- if (in != null)
- in.close();
- } catch (IOException e) {
- Log.e("db-error", e.toString());
- }
- }
- }
-
- }
Android編程心得-在Assets檔案夾中放入.sql檔案實現建立SQlite表的操作