blog

Home / DeveloperSection / Blogs / SQLite - ATTACH DATABASE COMMAND

SQLite - ATTACH DATABASE COMMAND

Tarun Kumar4871 11-Sep-2015

The ATTACH DATABASE statement allows you to attach multiple database file to the current database connection. The name that occurs after the AS keyword is the name of the database used internally by SQLite.


The database names main and temp are reserved for the primary database and database to hold temporary tables and other temporary data objects. Both of these database names exist for every database connection and should not be used for attachment, otherwise, you will get a warning message. The main and temp databases cannot be attached or detached.

 

Syntax:

 ATTACH DATABASE 'DatabaseName' As 'Alias-Name';

This command will also create a database in case database is already not created, otherwise, it will just attach database file name with logical database 'Alias-Name'.

 

Example:

First, we will create a Database:

D:\sqlite>sqlite3 contactDB.db
sqlite> .database
seq  name             file
---  ---------------  ------------------------
0    main             D:\sqlite\contactDB.db


In the above example shows that the main database is appearing and another database temp is hidden.

 

now to check the database you currently created is exist or not, use .database statement:

D:\sqlite> .database
seq  name             file
---  ---------------  ------------------------
0    main             D:\sqlite\contactDB.db

 

Now, if you want to attach an existing database contactDB.db, then ATTACH DATABASE statement would be as follows:

 D:\sqlite> ATTACH DATABASE 'contactDB.db' as 'CONTACT';

 

Use SQLite .database command to display attached database.

sqlite>.database
seq     name             file
---     --------------   ----------------------
0       main             /home/sqlite/contactDB.db
2       CONTACT          /home/sqlite/contactDB.db

 

The database names main and temp are reserved for the primary database and database to hold temporary tables and other temporary data objects. Both of these database names exist for every database connection and should not be used for attachment.


Now we are going to attach the database main and temp and look the result below, you will get a warning message something as follows:

D:\sqlite>  ATTACH DATABASE 'contactDB.db' as 'TEMP';

Error: database TEMP is already in use


D:\sqlite>  ATTACH DATABASE 'contactDB.db' as 'main';

Error: database TEMP is already in use


Updated 26-Feb-2018

Leave Comment

Comments

Liked By