Somk
Somk

Reputation: 12047

Android How to append SQLite database

I have a database created from a file in my assests folder. When the app is upgraded I want the new file in that folder to add (append) to the current database. I am currently trying to use this script below, but it is not working. I is just not adding to the db.

        //Open your local db as the input stream
        InputStream myInput = myContext.getAssets().open(STATIC_DB_NAME);

        // Path to the just created empty db
        String outFileName = STATIC_DB_PATH + STATIC_DB_NAME;

        //Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(outFileName);

        //transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer))>0){
            myOutput.write(buffer, 0, length);
        }

        //Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close(); 

Upvotes: 0

Views: 675

Answers (1)

Chris
Chris

Reputation: 23181

You should look at using the SQLLiteOpenHelper and implementing the onUpgrade method. In that method (only called when your database version number -- something you maintain-- is incremented), you can then open your asset file and use it to execute inserts/updates into the sqllite DB.

So in this case, store the SQL commands in the file and then read each line and run with db.execSQL:

BufferedReader reader = new BufferedReader(new FileReader(STATIC_DB_NAME));
String line  = reader.readLine();
while(line != null){
  db.execSQL(line); 
  line = reader.readLine();
}
reader.close();

Upvotes: 1

Related Questions