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