简体   繁体   中英

How to close SQLite database connection when using Python and Jupyter Notebook

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

您的代码似乎没问题,即使在调用conn.close()之后, print(conn)也将始终<sqlite3.Connection object at 0x######>返回一个<sqlite3.Connection object at 0x######>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM