Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 920
Cesar Hernandez Avatar asked Oct 18 '22 10:10

Cesar Hernandez


2 Answers

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!

like image 100
Cesar Hernandez Avatar answered Oct 21 '22 09:10

Cesar Hernandez


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!

like image 23
FlipperPA Avatar answered Oct 21 '22 11:10

FlipperPA