Home > database >  Add parameter within SQL Query - Python
Add parameter within SQL Query - Python

Time:11-05

I have defined a parameter called CODE.

CODE is a list of strings, for instance 'Car', 'Bike', 'Boat' and so on.

I need to execute SQL Querys that have the following pattern:

Select * from Table when CODE=Car

Or

Select * from Table when CODE=Bike

and so on.

Is it posible to use the parameter directly in the Query?

Like somenthing thike the following:

Select * from Table when CODE = Parameter CODE?

Edit:

Im using Python to make the Query. Variable CODE comes from a colomn of a DataFrame as it follows:

import pandas as pd
import pyodbc                                              

CODE=Table1['CODE']

dbconnection=pyodbc.connect('Driver={SQL Server};'  
'Server=XXXX,1234;'                           
'Database=AAAA;'
'Trusted_Connection=yes;')

sql="SELECT * FROM DATABASE  WHERE CODE = 'Bike'"

Selection=pd.read_sql(sql,dbconnection)

CodePudding user response:

You can use Python string formatting to replace the value. One type of formatting is the f-string syntax

#OLD (your approach)
sql="SELECT * FROM DATABASE  WHERE CODE = 'Bike'"

#NEW - with formatting
sql=f"SELECT * FROM DATABASE  WHERE CODE = '{CODE}'"

CodePudding user response:

If it isn't a long list of values in CODE, then you can do the following:

select * from Table where CODE IN ('Car', 'Bike', 'Boat', 'Motor', ...);
  • Related