Reputation: 108
I am using Jupyter Notebook to query an SQLite database running on a Raspberry Pi. I'm a beginner and I'm trying to learn to write 'good' Python and other threads say I should close the database connection after I have finished with it. I had been using
if conn:
conn.close()
but this morning I decided to try experimenting with with
so to check it was working I added print(conn)
. This returned <sqlite3.Connection object at 0x6d13####>
. More searching showed that with
will commit but not close SQLite connections, so I added
with closing(sqlite3.connect(db_file)) as conn:
which according to that same link should fix it. But print still returned an object. I then tried adding the print test on my original if and .close() method but that still returned an object. Is there something wrong with both my close methods, or am I misunderstanding what print(conn)
is telling me, or is there something about Jupyter that is stopping either method from closing the connection? This link suggests that Jupyter might be the problem? If it is Jupyter, how should I close the connection or do I just stop worrying about it?
Thanks for your help
Upvotes: 0
Views: 1442
Reputation: 71
I needed to use two different sqlite databases in Jupyter. The problem was that even if I started the second connection with a different name, the program was still using the first one.
I solved the problem by assigning None to the connection
conn.close()
conn = None
and only then I was able to connect to the second database.
I know that it doesn't makes sense, but it works.
Upvotes: 1
Reputation: 1
Your code appears to be fine, print(conn)
will always return a <sqlite3.Connection object at 0x######>
, even after conn.close()
is called.
Upvotes: 0