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
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With