Cesar Hernandez
Cesar Hernandez

Reputation: 135

Error when calling a procedure from pyodbc

This is my first question here. So, I am sorry if it is repeated or the formatting is off. I searched through other questions and the error is common but appears on multiple situations.

I have a very simple python code where I want to execute a procedure in MSSQL from pyodbc.

import pyodbc
conn = pyodbc.connect(r'DSN=myDSN')
cursor = conn.cursor()
query = r'{call myproc}'
cursor.execute(query)

I am using call instead of exec after reading that ODBC uses call for executing procedures in MSSQL.

The error I am getting is the following:

Traceback (most recent call last):
File "myscript.py", line 26, in <module>
cursor.execute(query)
pyodbc.ProgrammingError: ('42000', '[42000] [Microsoft][SQL Server Native Client 11.0][SQL Server]The current transaction has aborted, and any pending changes have been rolled back. Cause: A transaction in a rollback-only state was not explicitly rolled back before a DDL, DML or SELECT statement.  (111233) (SQLExecDirectW)')

Thanks for the help

Upvotes: 5

Views: 4028

Answers (3)

pradsav
pradsav

Reputation: 71

I had issue with executing the Stored procedure using the SQL server 2008. The first step I did is to go to control panel > Administrative tools > Data Sources (ODBC) > add the driver

enter image description here

The only change I made in my python code is use "{call procdev_2017}". I got an error when I tried using exec instead of call

import pyodbc


conn = pyodbc.connect(driver='{SQL Server Native Client 11.0}', server='XXXXXXX', database='XXX',
                      trusted_connection='yes', autocommit=True)
bepcur = conn.cursor()
ipcur.execute("{call procdev_2017}")

Upvotes: 0

Cesar Hernandez
Cesar Hernandez

Reputation: 135

In case someone is having the same issue. I was able to find out what the problems was. When you open a connection with DSN, the autocommit is set to False. For some reason, this should be True for the code to work (this depends largely on what I was doing on MSSQL).

import pyodbc
conn = pyodbc.connect(r'DSN=myDSN', autocommit=True)
cursor = conn.cursor()
query = r'{call myproc}'
cursor.execute(query)

This runs well!

Upvotes: 2

FlipperPA
FlipperPA

Reputation: 14311

Here are two examples on how you can execute a stored proc in MS SQL Server through pyodbc:

Passing a NULL, and the VARCHAR 'tallen' as positional parameter variables:

cursor.execute('EXEC usp_get_user_data ?, ?', None, 'flipperpa')

Passing two VARCHAR values as named parameter variables:

cursor.execute('EXEC usp_get_user_data @user_full_name = ?, @user_username = ?', 'flip', 'flipperpa')

Then to loop through the returned data:

rows = cursor.fetchall()
for row in rows:
    # Do stuff
    print(row.user_id)

Good luck!

Upvotes: 1

Related Questions