How to create SQLite database in Android by importing from SQL file?

I have a large text file containing SQL CREATE TABLE and INSERT . How to import this file into SQLiteOpenHelper onCreate method?

Or is there an acceptable way to directly use the database file?

I need this to be compatible with Android 1.6.

+7
source share
4 answers

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

Alternatively, you can β€œsend” SQLite db with your application - see this link to give you some ideas ...

Using Native SQLite Database in Android Applications

+4
source

I had to solve the same problem. There was no direct way to do this, so I put the file in the res / raw directory and used openRawResource to get an InputStream. Then I read the lines until it ends with ; . Then I passed the expression to the sqlite database.

Hope someone else comes along with a better way, but I thought I would just add the way I did it.

+5
source

After the answer by Steve Prentice. This is 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
source

The problem with importing your own sqlite db file is that you need to make sure that the version of the kernel with which you created the file matches the version of the kernel on the Android device to which db is installed. By running the SQL script file, you will verify that the database is created using the mechanism actually installed on the Android device.

0
source

All Articles