i have a database "softDb" in my app and on new version i create new database "softDatabase".
how to do copy table and data or only data from old database (softDb ) to new database softDatabase?
i have a database "softDb" in my app and on new version i create new database "softDatabase".
how to do copy table and data or only data from old database (softDb ) to new database softDatabase?
It's as simple as this, if you want to change the existing DB scheme, you can Alter tables in onUpgrade method. use this method to drop tables, add tables, or do anything else it needs to upgrade to the new schema version.
If you want to copy data of one table to another, store it in a temp db or Arraylist, once you alter the table insert it to new Table.
when you update database that time onUpgrade() method call.In onUpgrade() method if you want to add or delete tabel ,db etc. if you want to copy all data in existing table to new table used below code in onUpgrade() method.
INSERT INTO X.TABLE(fieldname1, fieldname2) SELECT fieldname1, fieldname2 FROM Y.TABLE;
if you want to copy the database to new database that time you used find path of old database file and then after copy hall database file into new database file like below code...
private void copyDataBaseFile()
{
Log.i("Database",
"New database is being copied to device!");
byte[] buffer = new byte[1024];
OutputStream myOutput = null;
int length;
// Open your local db as the input stream
InputStream myInput = null;
try
{
myInput =new FileInputStream("/data/data/com.example.adruser.stackoverflow/databases/"+"MyDb");
// transfer bytes from the inputfile to the
// outputfile
myOutput =new FileOutputStream("/data/data/com.example.adruser.stackoverflow/databases/"+ "MyDb2");
while((length = myInput.read(buffer)) > 0)
{
myOutput.write(buffer, 0, length);
}
myOutput.close();
myOutput.flush();
myInput.close();
Log.i("Database",
"New database has been copied to device!");
}
catch(IOException e)
{
e.printStackTrace();
}
}
above code create new database file and copy old db data. also need to add to permission..
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>