8

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

1 Answer 1

12

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks Martjin, is there any way you know of to attach a database like I am trying to do? I want a nested table structure.
@AlexG: just execute your ATTACH statements each time you connect.
@AlexG: however, if you are always need for those tables to exist, why are you putting them into a separate database? Just put them all in the same database if you need access to them each and every time.
Good advice, I'll do one of those two options

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.