SQLite Attach Database
Suppose a situation where multiple databases are available at the same time and you want to use any of them. SQLite's ATTACH DATABASE statement is used to select a particular database; after using this command, all SQLite statements will be executed under the attached database.
Syntax
The basic syntax of SQLite's ATTACH DATABASE statement is as follows:
ATTACH DATABASE file_name AS database_name;
If the database has not yet been created, the above command will create one; if the database already exists, it binds the database file name to the logical database 'Alias-Name'.
The opened database and the database attached using ATTACH must be located in the same folder.
Example
If you want to attach an existing database testDB.db, then the ATTACH DATABASE statement will be as follows:
sqlite> ATTACH DATABASE 'testDB.db' as 'TEST';
Use the SQLite .database command to display the attached databases.
sqlite> .database
seq name file
--- --------------- ----------------------
0 main /home/sqlite/testDB.db
2 test /home/sqlite/testDB.db
Database names main and temp are reserved for the main database and for the database that stores temporary tables and other temporary data objects. These two database names can be used for every database connection and should not be used for attaching, otherwise a warning message will be produced, as shown below:
sqlite> ATTACH DATABASE 'testDB.db' as 'TEMP';
Error: database TEMP is already in use
sqlite> ATTACH DATABASE 'testDB.db' as 'main';
Error: database main is already in use;