Hello, forgive me I’m new to programming and Python.
I am trying to write a function that implements pyodbc to execute any stored procedures in SQL Server that I pass as an argument. Also, these stored procedures can have different numbers of parameters. The following code works fine but I was wondering if there is a way of achieving the same aim more succintly.
Thanks in advance.
import pyodbc
import os
class SqlDb:
cnx = os.environ["BFDBCNX"]
def Exec(self, proc, param1 = None, param2 = None, param3 = None, param4 = None, param5 = None):
try:
connection = pyodbc.connect(self.cnx)
cursor = connection.cursor()
if (param1 is None):
cursor.execute("{CALL " + proc + "}")
dataset = cursor.fetchall()
return dataset
elif(param2 is None):
cursor.execute("{CALL " + proc + "(?)}", param1)
connection.commit()
elif(param3 is None):
cursor.execute("{CALL " + proc + "(?, ?)}", param1, param2)
connection.commit()
elif(param4 is None):
cursor.execute("{CALL " + proc + "(?, ?, ?)}", param1, param2, param3)
connection.commit()
elif(param5 is None):
cursor.execute("{CALL " + proc + "(?, ?, ?, ?)}", param1, param2, param3, param4)
connection.commit()
else:
cursor.execute("{CALL " + proc + "(?, ?, ?, ?, ?)}", param1, param2, param3, param4, param5)
connection.commit()
except pyodbc.Error as ex:
print("An error occurred in SQL Server:", ex)
connection.rollback()
finally:
if 'connection' in locals():
connection.close()