rid
rid

Reputation: 63442

How do I create an SQLite database in Android by importing from an SQL file?

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.

Upvotes: 8

Views: 18087

Answers (4)

Androiderson
Androiderson

Reputation: 17083

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);
    }

Upvotes: 5

Quasaur
Quasaur

Reputation: 1365

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.

Upvotes: 0

Squonk
Squonk

Reputation: 48871

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

Upvotes: 4

Steve Prentice
Steve Prentice

Reputation: 23514

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.

Upvotes: 6

Related Questions