-6

I have below requirement in python,where I need to pass date and id at run time.

query_str="select * from test_table where data_date = '${data_date}' and id = ${id}"

Where data_date is string column and id is big int column. 

If i'm passing data_date as 2015-01-01 and id as 1, it should replace the parameters as below.

Output : select * from test_table where data_date = '2015-01-01' and id = 1
SAMO
  • 458
  • 1
  • 3
  • 20
Satish Kumar Reddy
  • 111
  • 1
  • 2
  • 5

1 Answers1

3

What you are actually asking about is called query parameterization and it has to be done right relying on what your database driver provides. This way you let your driver handle the proper escaping and python-to-database type conversions.

Depending on the driver, the placeholder style can differ, but %s is the most common:

query_str = """
    select * 
    from test_table 
    where data_date = %s and id = %s
"""
params = ('2015-01-01', 1)
cursor.execute(query_str, params)

where cursor is your database connection cursor instance.

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • This query parameterization is for pyspark SQL execution. I couldn't find any database driver for this purpose. That's the reason I'm looking for parameterization using python functions and execute the parameterized query. – Satish Kumar Reddy Jul 08 '16 at 19:26