How do I create an SQLite database in Android by i

2019-04-25 14:07发布

问题:

I have a big text file containing SQL CREATE TABLE and INSERT statements. How do I import this file in the SQLiteOpenHelper onCreate method?

Or, is there an accepted way of using the binary database file directly?

I need this to be compatible with Android 1.6.

回答1:

In the SQLiteOpenHelper onCreate() method you can just use db.execSQL(...) but that depends on how your 'text file' is structured (and how big it is).

Alternatively, you can 'ship' a SQLite db with your app - see this link to give you some ideas...

Using your own SQLite database in Android applications



回答2:

I had to solve the same problem. Couldn't find a direct way to do it, so I put the file into the res/raw directory and used openRawResource to get an InputStream on it. I then read lines until one ended with a ;. I then passed the statement to the sqlite database.

Hopefully someone else comes along with a better way, but I thought I would just add the way that I ended up doing it.



回答3:

Following Steve Prentice's answer. That's my implementation:

mydb.sql file in res/raw

CREATE TABLE table1(col1 INTEGER PRIMARY KEY, col2 TEXT);
CREATE TABLE table2(col1 INTEGER PRIMARY KEY, col2 TEXT, col3 INTEGER);

MyClass.java

    InputStream inputStream = context.getResources().openRawResource(R.raw.mydb);

    String queries = "";
    try {
        queries = IOUtils.toString(inputStream);
    } catch (IOException e) {
        Util.logException(e);
    }

    for (String query : queries.split(";")) {
        db.execSQL(query);
    }


回答4:

The problem with importing your own sqlite db file is that you have to make sure the engine version you created the file with matches the engine version on the Android device the db is being installed to. by running the SQL script file you ensure that the database is being created using the engine actually installed on the Android device.