Multiple database operations from SQL query

I have two database instances SQLiteDatabase. And I need to copy data from one to another. I need to execute this query:

INSERT INTO `toDB`.`tableName` SELECT * FROM `fromDB`.`tableName` 

So how can I do this in my database instances? How to replace toDB and fromDB?

+3
source share
2 answers

Never tried, but it should work this way:

you must ATTACH another database at the SQLite level, so sqlite can access it directly.

For example, you open the database, which should be toDB, and you issue the following command (via execSQL)

ATTACH DATABASE '/data/data/your.package/databases/dbname.db' AS fromDB

you should now have access to another database and you can do

INSERT INTO main.tableName SELECT * FROM fromDbB.tableName

"main" .

Context # getDatabasePath, , .

+2

, :

    DatabaseHelper dbHelper = DatabaseHelper.create(CMOSApplication.getInstance());
    SQLiteDatabase db = null;
    try {
        db = dbHelper.getWritableDatabase();
        db.execSQL("attach database ? as oldDB",
                new String[] { CMOSApplication.getInstance().getDatabasePath("cmos_database").getPath() });
        db.execSQL("insert into task select * from oldDB.task");
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if(db != null){
            try {
                db.execSQL("detach oldDB");
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
0

All Articles