- Posted on
- • blog
Copying data from an SQLite3 database partially or complete to another database
- Author
-
-
- User
- tim
- Posts by this author
- Posts by this author
-
If you want to transfer parts (or a complete) database file to another one, you don't need to implement your own transport mechanism. You can easily do this from within SQLite itself.
Copying a complete table to another database
Assuming you have a database aDB holding the table with records and that table should be copied to a different database bDB, you can just combine the ATTACH and CREATE TABLE .. AS statements built into SQLite.
First, open aDB using sqlite_open() and then attach the target database file new.db under the name bDB:
ATTACH DATABASE 'new.db' AS bDB;
Now copy the table from the source to the target:
CREATE TABLE bDB.newtable AS SELECT * FROM oldTable;
Alternatively, if you're importing data from bDB into the current database:
CREATE TABLE newtable AS SELECT * FROM bDB.oldTable;
This copies the data but does not include field attributes such as PRIMARY KEY from the original table.
You can also add a WHERE clause to filter specific rows.
Merge data from other databases
To merge or selectively copy data, use INSERT INTO.
You must first create the table manually and then reference columns explicitly:
INSERT INTO newtable (field1, field2)
SELECT otherfield1, otherfield2 FROM bDB.oldTable;
Cleaning up
Once finished, detach the external database:
DETACH DATABASE bDB;
The new.db file is now closed and saved.
Note:
SQLite limits the number of simultaneously attached databases.
By default, the limit is 10 (SQLITE_MAX_ATTACHED).
It cannot be increased beyond 125.