3

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.

2
  • 1
    What code have you tried and why didn't it work for you? (Error messages?) Have you tried reading through the pandas.read_sqlquery documentation yet? You can pass in parameters via the params tuple. Commented Mar 18, 2021 at 12:25
  • @AlwaysLearning I tried to do that as is described at docs.sqlalchemy.org/en/13/core/connections.html (Calling Stored Procedures) and received error: 'pyodbc.Cursor' object has no attribute 'callproc' Commented Mar 18, 2021 at 13:21

1 Answer 1

7

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.
"""
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.