SQLite Attach Database

Suppose a situation where there are multiple databases available at the same time, and you want to use any one of them. SQLite'sATTACH DATABASEstatement is used to select a specific database. After this command is used, 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 been created yet, the above command will create a database. If the database already exists, it binds the database file name with 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 databasetestDB.db, then the ATTACH DATABASE statement will be as follows:

sqlite> ATTACH DATABASE 'testDB.db' as 'TEST';

Use SQLite.databasecommand to display the attached databases.

sqlite> .database
seq  name             file
---  ---------------  ----------------------
0    main             /home/sqlite/testDB.db
2    test             /home/sqlite/testDB.db

Database namesmainandtempare reserved for the main database and 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 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;
Other extensions