user6189
user6189

Reputation: 673

SQLite: Easiest way to copy a table from one database to another?

I have two sqlite databases and want to copy a table from database A to database B. The other tables in database A should not be copied. What is the easiest way to do that in Java?

I could definitively do something like Select * from A and then insert all of this into database B, but shouldn't there a better way?

Upvotes: 30

Views: 26436

Answers (2)

mivk
mivk

Reputation: 14824

Why do you want to do that in Java? You can do it directly at the command-line, by dumping your table, and reading it into your other database :

sqlite3 A.sqlite ".dump some_table" | sqlite3 B.sqlite

If you need to drop the existing table in "B.sqlite" first, you can use the -cmd switch in the second part, to "run command before reading stdin" :

sqlite3 A.sqlite ".dump some_table" \
| sqlite3 -cmd "DROP TABLE IF EXISTS some_table" B.sqlite

Upvotes: 12

Colonel Thirty Two
Colonel Thirty Two

Reputation: 26569

Open the database you are copying from, then run this code to attach the database you are copying to and then copy a table over.

ATTACH DATABASE 'other.db' AS other;

INSERT INTO other.tbl
SELECT * FROM main.tbl;

Upvotes: 43

Related Questions