How to call a column name dynamically in a sql query, based on the select bar option!

I have a side bar, named project_bar when all values in the specific column is shown as selectbox.

project_bar = st.sidebar.selectbox('Select Project Name', study["ProjectName"])
               

query1= " select BusinessUnit from [TestTable].[dbo].[ProjectDetails](nolock) where ProjectName = +'project_bar '; 
#I need the value to be dynamically filled here,on whatever the user selects from the sidebar (project_bar)
study1 = pd.read_sql(query1, cnxn)
st.write(study1)

I am trying to execute a query where I have the β€œwhere” condition, which gets dynamically filled from the select bar option.

Hi @Hiba_Fatima,

You could try using f-strings :slightly_smiling_face:

project_bar = st.sidebar.selectbox('Select Project Name', study["ProjectName"])

query1= f"select BusinessUnit from [TestTable].[dbo].[ProjectDetails](nolock) where ProjectName = '{project_bar}';"

study1 = pd.read_sql(query1, cnxn)
st.write(study1)

Best, :balloon:
Snehan

2 Likes

Hi @Hiba_Fatima,

Be aware that constructing sql commands using string formatters opens up the possibility of SQL injection. The way @snehankekre is suggesting should be fine since the input in controlled by the selection box :slight_smile: But if you include anything like a textbox you need to watch out.

image

1 Like

When I am using the f-string, I am getting an error

DatabaseError: Execution failed on sql β€˜select BusinessUnit from [TestTable].[dbo].ProjectDetails where ProjectName = Test;’: (β€˜42S22’, β€œ[42S22] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid column name β€˜Test’. (207) (SQLExecDirectW)”)

when I am running this query, it gives the right output

query1= "select BusinessUnit from [TestTable].[dbo].ProjectDetails where ProjectName = β€˜Test’; "

You need to add single quotes outside the f-string placeholder:

v = "test"
print(f"This is a '{v}'")

>>> This is a 'test'

2 Likes

How else would you properly format a SQL query to avoid something like this?