mkleehammer / pyodbc

Python ODBC bridge
https://github.com/mkleehammer/pyodbc/wiki
MIT No Attribution
2.88k stars 562 forks source link

One execute Stored Procedure causes multiple calls to store procedure in the database #1106

Closed alejandro2196 closed 1 year ago

alejandro2196 commented 1 year ago

Environment

Issue

I made the following script to handle the connection to the database and to be able to execute stored procedures.

Procedures that simply return data behave correctly.

In stored procedures that perform inserts, it was found that even if .execute is only called once, executing the stored procedure call multiple times will result in multiple inserts. I know that it is called several times because with the getdate() that I insert I can see that there are multiple equal inserts with dates very close together.

I don't know how I can fix or control this. I haven't found anyone that has.

Thanks.

CODE

import pyodbc

class SQLManagmentConnection:

#Constructor
def __init__(self, server, database, user, password, driver):

    self.server = server; 
    self.database = database
    self.username = user
    self.password = password
    self.driver = driver

def connect(self):

    #print ('Connecting to database...')
    self.cnxn = pyodbc.connect('DRIVER={'+ self.driver +'};SERVER='+self.server+';DATABASE='+self.database+';UID='+self.username+';PWD='+ self.password, autocommit=True)
    self.cursor = self.cnxn.cursor()
    #print ('Connected database')

def close(self):
    self.cursor.close() 
    self.cnxn.close()

def execute(self, procedure, parameters, parametersName):

    parametersName_comma_separated = "=?, @".join(parametersName)

    if parametersName_comma_separated == "":
        sql = """\
        DECLARE @return_value int;
        EXEC    @return_value = """ + procedure +""";  
        SELECT  'Return Value' = @return_value;
        """
        crsr = self.cnxn.execute(sql)

    else:

        sql = """\
        EXEC """ + procedure + """ @"""+ parametersName_comma_separated +"""=?
        """
        crsr = self.cnxn.execute(sql, parameters)

    data = crsr.fetchall()
    #crsr.commit()

    return data
v-chojas commented 1 year ago

executing the stored procedure call multiple times will result in multiple inserts

That seems normal? I'm not sure what else you're expecting?

If you post an ODBC trace, maybe that will make it clearer?