Search code examples
pythonmysqlfiltercursor

Python - Apply a filter on query using a Python Parameter


I've a script that makes a query to my database on MySQL. And my doubt is if I can pass any parameter to that query through Python.

For example, on the following script I want to calculate the date_filter using Python and then apply that filter on the query.

now = dt.datetime.now()
date_filter = now - timedelta(days=3)

dq_connection = mysql.connector.connect(user='user', password='pass', host='localhost', database='db')
engine = create_engine('localhost/db')
cursor = connection.cursor(buffered=True)
query = ('''
SELECT *
FROM myTable
WHERE date >= ''' + date_filter + '''
''')

I try it on that way but I got the following error:

builtins.TypeError: can only concatenate str (not "datetime.datetime") to str

It is possible to apply the filter like that?

Thanks!


Solution

  • Yes, you can do it. To avoid sql injections, the best way is not using the python formatting facilities, but the sql parameters & placeholders (see that you don´t need the single quotes ' as the placeholder does the job and converts the type of the variable):

    now = dt.datetime.now()
    date_filter = now - timedelta(days=3)
    
    dq_connection = mysql.connector.connect(user='user', password='pass', host='localhost', database='db')
    engine = create_engine('localhost/db')
    cursor = db_connection.cursor(buffered=True)
    query = "SELECT * FROM myTable WHERE date >=%s"
    cursor.execute(query,(date_filter,))
    

    Also, you had a mistake in your cursor, it should be db_connection.cursor. The last comma after date_filter is ok because you need to send a tuple. In case you need more than one paremeter, you can place more than one placeholder:

    query = "SELECT * FROM myTable WHERE date >=%s and date<=%s"
    cursor.execute(query,(date_filter,other_date))