Op 18/11/2026 om 17:46 schreef Klaus Jantzen via Python-list:
Hello,
I got the following code from the website shown in the code.
=======
#!/usr/bin/python3.14
#
# https://runebook.dev/en/docs/python/library/sqlite3/sqlite3.Warning
import sqlite3
try:
with sqlite3.connect(':memory:') as conn:
cursor = conn.cursor()
# Use executescript() for multiple statements
sql_script = """
DROP TABLE IF EXISTS test_table;
CREATE TABLE test_table (data TEXT);
INSERT INTO test_table (data) VALUES ('Hello');
"""
cursor.executescript(sql_script)
print("Multiple statements executed successfully with
executescript().")
except sqlite3.Error as e:
print(f"Error caught: {e}")
=======
# ResourceWarning: unclosed database in <sqlite3.Connection object at
0x7f0ff158bdf0>
=======
That code is supposed to avoid that message, but I still get the
resoure warning.
Is something wrong with my python installation (compiled this morning)
or is that a python error?
Somewhat confusingly the sqlite3.connect() context manager does not
close the connection. I didn't know that, it's something I just learned
because your post triggered my interest and I had a look at the
documentation. See
https://docs.python.org/3/library/sqlite3.html#how-to-use-the-connection-context-manager:
"Note: The context manager neither implicitly opens a new transaction
nor closes the connection. If you need a closing context manager,
consider using contextlib.closing()."
So what you can do is first import contextlib, then
try:
with contextlib.closing(sqlite3.connect(':memory:')) as conn:
cursor = conn.cursor()
# ... and the rest of your code
It's not entirely clear to me whether that still automatically commits
or rolls back open transactions.
--
"If you don't read the newspaper, you're uninformed. If you read the newspaper,
you're mis-informed."
-― Onbekend (dikwijls toegeschreven aan Mark Twain, waarschijnlijk
onterecht)
--
https://mail.python.org/mailman3//lists/python-list.python.org