1

I can read a text file which is in the assets folder. But now I have a DB creation query in the text file; how can I execute that query in Android? Please don't ask why I want to keep queries in a plain text file.

4

1 回答 1

4

您应该使用 SqliteOpenHelper 并覆盖 onCreate 方法。在该方法中,您应该从资源中读取文件并执行它。

请参阅this了解如何使用 SqliteOpenHelper

然后从资源中读取文件只需这样做(从这里):

    @Override
    public void onCreate(SQLiteDatabase database) {
      Resources res = getResources();
      InputStream in_s = res.openRawResource(R.raw.sql);
      byte[] b = new byte[in_s.available()];
      in_s.read(b);
      String sql = new String(b);
      database.execSQL(sql);
    }

然后您还需要实现 onUpgrade (因为它被标记为抽象),但您不需要在该方法中执行任何操作,直到您决定更改数据库的结构。

于 2012-06-27T07:03:24.047 回答