Skip to content

cursor.execute() with reset_cursor=False raises ProgrammingError: Invalid cursor state #506

@dlevy-msft-sql

Description

@dlevy-msft-sql

Describe the bug

Calling cursor.execute() with reset_cursor=False raises ProgrammingError: Invalid cursor state even after fully consuming the previous result set with fetchall().

The wiki documents reset_cursor as a parameter that, when False, skips freeing and reinitializing the statement handle so the prepared plan can be reused. In practice, any call with reset_cursor=False fails.

Exception message: Driver Error: Invalid cursor state; DDBC Error: [Microsoft]Invalid cursor state

To reproduce

import mssql_python

conn = mssql_python.connect(connection_string)
cursor = conn.cursor()

# First execute works fine
cursor.execute(
    "SELECT TOP 1 ProductID FROM Production.Product WHERE ProductSubcategoryID = ?",
    (1,),
)
row = cursor.fetchone()
print(row.ProductID)  # Works

# Consume remaining results
_ = cursor.fetchall()

# Second execute with reset_cursor=False fails
cursor.execute(
    "SELECT TOP 1 ProductID FROM Production.Product WHERE ProductSubcategoryID = ?",
    (2,),
    reset_cursor=False,
)
# Raises ProgrammingError: Invalid cursor state

Note: The same sequence works fine with the default reset_cursor=True.

Expected behavior

cursor.execute() with reset_cursor=False should reuse the prepared statement handle and execute successfully, as documented in the wiki.

Further technical details

Python version: 3.14.0
mssql-python version: 1.4.0
SQL Server version: SQL Server 2022
Operating system: Windows 11 (ARM64, running x64 emulation)

Additional context
Tested against AdventureWorks2022. The default behavior (reset_cursor=True) works correctly. Only reset_cursor=False triggers the error.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingtriage neededFor new issues, not triaged yet.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions