rams
rams

Reputation: 123

how to copy the contents from one database to another database in sqllite android?

I am using two databases in my android application assume A and B.I want to copy the contents of database A to database B. How it can be achieved?. Am trying like this.Its not working.Please suggest the solution.

 String alter_query3="insert into B.TableName1 select * from  A.TableName2";
     db.execSQL(alter_query3);  

Upvotes: 0

Views: 75

Answers (3)

samsad
samsad

Reputation: 1241

Well Yes, As far as I know it would be possible through this code:

Example :

INSERT INTO db2.tbl SELECT * FROM db1.tbl

Upvotes: 0

laalto
laalto

Reputation: 152817

First ATTACH one database to the other and then use the INSERT INTO ... SELECT ... syntax:

-- working on database "A"
ATTACH '/path/to/other/database.db' AS B;
INSERT INTO TableName1 SELECT * FROM B.TableName2;

Upvotes: 1

Md. Shahadat Sarker
Md. Shahadat Sarker

Reputation: 849

Get data/contents from database A and make a list/arraylist:

public ArrayList<Customer> getCustomerFromA() {
        String sql = "SELECT * FROM " + DB_TABLE.CUSTOMER ;
        ArrayList<Customer> customerList = new ArrayList<Customer>();

        Cursor cursor = dbA.rawQuery(sql, null);
        Customer customer = null;
        if (cursor.moveToFirst()) {
            customer = new Customer();
            customer.setCode(cursor.getString(cursor.getColumnIndex(DB_TABLE.CUSTOMER_CODE)));
            customer.setName(cursor.getString(cursor.getColumnIndex(DB_TABLE.CUSTOMER_NAME)));
            customer.setAddress(cursor.getString(cursor.getColumnIndex(DB_TABLE.CUSTOMER_ADDRESS)));
            customerList.add(customer);
        }
        cursor.close();

        return customerList;
    }

And then intert into database B:

public void insertCustomerListToB(ArrayList<Customer> customerList) {

    for (Customer customer : customerList) {
        ContentValues cv = new ContentValues();
        cv.put(DB_TABLE.CUSTOMER_CODE, customer.getCode());
        cv.put(DB_TABLE.CUSTOMER_NAME, customer.getName());
        cv.put(DB_TABLE.CUSTOMER_ADDRESS, customer.getAddress());
        dbB.insert(DB_TABLE.CUSTOMER, null, cv);
    }

}

Customer is an Entity Class

Upvotes: 0

Related Questions