Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attach database in sqlite3 with python

Tags:

python

sqlite

For this example I have db_master.sqlite and db_1.sqlite in the working directory.

Everything seems to be working fine when I do this:

import sqlite3
conn = sqlite3.connect('db_master.sqlite')
c = conn.cursor()
c.execute('ATTACH DATABASE "db_1.sqlite" AS db_1')
c.execute('SELECT * FROM db_1.my_table')
conn.commit()
c.fetchall()

I get the column data back as expected. But when I close the connection and re-open it, the database no longer appears to be attached.

conn.close()
conn = sqlite3.connect('db_master.sqlite')
c = conn.cursor()
c.execute('SELECT * FROM db_1.my_table')
c.fetchall()

OperationalError: no such table: db_1.my_table

like image 706
AlexG Avatar asked Nov 03 '16 18:11

AlexG


People also ask

What is Attach database in SQLite?

The ATTACH DATABASE statement adds another database file to the current database connection. Database files that were previously attached can be removed using the DETACH DATABASE command.

How fetch data from sqlite3 database in Python?

SQLite Python: Querying Data First, establish a connection to the SQLite database by creating a Connection object. Next, create a Cursor object using the cursor method of the Connection object. Then, execute a SELECT statement. After that, call the fetchall() method of the cursor object to fetch the data.


1 Answers

You attach databases to your connection, not to a specific database. You'll have to re-attach each time you create a new database connection.

From the ATTACH DATABASE documentation:

The ATTACH DATABASE statement adds another database file to the current database connection.

Emphasis mine.

like image 100
Martijn Pieters Avatar answered Sep 29 '22 22:09

Martijn Pieters