Monday, October 7, 2019

What is Detach Database in SQLite? How to use it?

SQLite Detach Database

In SQLite detach database command allows you to dissociate database from the current connection. The database which we are trying to detach is the one which we already opened with ATTACH DATABASE command.

In case if the same database file has been attached multiple times in sqlite then the detach database statement will only detach mentioned name instance and remaining attachments will continue with current session.

If we use sqlite detach command on database which is an in-memory or temporary, the database will destroy and content will be lost completely.

In SQLite we cannot detach main or temp databases. The DETACH command will fail if issued inside a transaction.

Syntax of SQLite Detach Database

Following is the syntax of using SQLite detach database statement.

DETACH DATABASE 'database_alias_name';
Here database_alias_name is the alias name of database that we give as name for the database when using ATTACH DATABASE command.

Example of SQLite Detach Database

First we will see what are the databases available in current connection for that run .databases command.

sqlite> .databases
When we run .databases command it returns following databases which are available in current connection.

seq  name             file
---  ---------------  ----------------------------
0    main             C:\sqlite\emp.db
2    myDB             c:\sqlite\db1.db
3    emp              c:\sqlite\emp.db
4    empDB            c:\sqlite\emp.db
Now, if you want to detach database named empDB then run following command.

sqlite> DETACH DATABASE empDB;
Now, again we will fire .databases meta command to see the list of attached databases in current connection.

sqlite> .databases
When we run above command it returns following list of databases available in current connection.

seq  name             file
---  ---------------  --------------------------
0    main             C:\sqlite\emp.db
2    myDB             c:\sqlite\db1.db
3    emp              c:\sqlite\emp.db
This is how we can use sqlite detach database statement to detach or disassociate database from current connection.

No comments:

Post a Comment

Lab 09: Publish and subscribe to Event Grid events

  Microsoft Azure user interface Given the dynamic nature of Microsoft cloud tools, you might experience Azure UI changes that occur after t...