Skip to content

sqlite3 - file stays opened even after connection is closed (still opened by the cursor?) #135117

Open
@Andrej730

Description

@Andrej730

Bug report

Bug description:

Python 3.11.9

Consider the snippet below.
It creates a new sqlite database, then closing the connection to it and trying to delete the file. On Windows it fails since sqlite file is still used by Python.

It seems the created cursor is still using the file, though all connections to it are closed.
Which is kind of unexpected, since when you close the connection to the database, connection object and all cursors are effectively become dead and they cannot be reopened, so nothing should be still using the file after connection is closed.

What helps is to close cursor explicitly (c.close() or just delete it del c).

Another detail - if we create a table, but don't insert anything to it, issue doesn't occur.

from pathlib import Path
import sqlite3

db_path = Path("new_db.sqlite")
if db_path.exists():
    db_path.unlink()

db = sqlite3.connect(db_path)
c = db.cursor()
c.execute("CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT)")

# Commenting out resolves the issue.
c.executemany("INSERT INTO test (value) VALUES (?)", [(f"value_{i}",) for i in range(1000)])

db.commit()
# c.close() # Required to avoid the error.
db.close()

# PermissionError:
# [WinError 32] The process cannot access the file because it is being used by another process: 'new_db.sqlite'
db_path.unlink()

CPython versions tested on:

3.11

Operating systems tested on:

Windows

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    Status

    No status

    Status

    Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions