SQLite Attach Database
Suppose you have multiple databases available at the same time and you want to use any of them. SQLite's ATTACH DATABASE statement is used to select a specific database. After using this command, all SQLite statements will be executed under the attached database.
Syntax
The basic syntax for SQLite's ATTACH DATABASE statement is as follows:
ATTACH DATABASE file_name AS database_name;
If the database has not been created, the above command will create a database. If the database already exists, it will bind 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, the ATTACH DATABASE statement will look like this:
sqlite> ATTACH DATABASE 'testDB.db' as 'TEST';
Use the SQLite .database command to display the attached database.
sqlite> .database
seq name file
--- --------------- ----------------------
0 main /home/sqlite/testDB.db
2 test /home/sqlite/testDB.db
The database names main and temp are reserved for the main database and the database storing temporary tables and other temporary data objects. These two database names can be used for each database connection and should not be used for attachment, otherwise, you will get a warning message, 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