0

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

2 Answers 2

1

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.

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

Comments

0

Your code appears to be fine, print(conn) will always return a <sqlite3.Connection object at 0x######>, even after conn.close() is called.

Comments

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.