[FIXED] How correctly execute a MSSQL stored procedure with parameters in Python

Issue

Currently i'm executing stored procedure that way:

engine = sqlalchemy.create_engine(self.getSql_conn_url())
query = "exec sp_getVariablesList @City = '{0}', @Station='{1}'".format(City, Station)
self.Variables = pd.read_sql_query(query, engine)

but at How set ARITHABORT ON at sqlalchemy was correctly noticed that that make that open to SQL injection. I tried different ways but without success. So how should I pass parameters to the MSSQL stored procedure to eliminate the risk of SQL injection? That can be with sqlalchemy or any other way.


Solution

Write your SQL command text using the "named" paramstyle, wrap it in a SQLAlchemy text() object, and pass the parameter values as a dict:

import pandas as pd
import sqlalchemy as sa

connection_uri = "mssql+pyodbc://@mssqlLocal64"
engine = sa.create_engine(connection_uri)

# SQL command text using "named" paramstyle
sql = """
SET NOCOUNT ON;
SET ARITHABORT ON;
EXEC dbo.breakfast @name = :name_param, @food = :food_param;
"""
# parameter values
param_values = {"name_param": "Gord", "food_param": "bacon"}
# execute query wrapped in SQLAlchemy text() object
df = pd.read_sql_query(sa.text(sql), engine, params=param_values)

print(df)
"""
                           column1
0  Gord likes bacon for breakfast.
"""


Answered By - Gord Thompson
Answer Checked By - Katrina (sql.easybugfix Volunteer)

Related Posts

Post a Comment