Skip to content Skip to sidebar Skip to footer

Passing Python Variable To Sql

I have a python script that I want to extract data to a list from a DB, and then print it out. Here is the code: sql = 'SELECT * FROM example WHERE column1 == 'string_value' AND co

Solution 1:

ValueError: operation parameter must be str

What is happening is that sql variable is a tuple, but execute() expects to see a string as the first positional parameter. What you meant was to parameterize the query by passing the query parameters to execute() separately:

sql= "SELECT * FROM example WHERE column1 = %s AND column2 = %s  AND column3 = %s "
c.execute(sql, (var1_str, var2_float, var3_str))

forrowin c.fetchall():
    query.append(row)

Solution 2:

"AND column3 = %s ",(var1_str, var2_float, var3_str)

String formatting requires a percent sign.

"AND column3 = %s " % (var1_str, var2_float, var3_str)

Not that I condone using string formatting when forming a sql query. If any of those values come from an untrusted source, you're opening yourself up to SQL injection attacks. Check the documentation of your DB interface to see if it has a safer way of including parameters.

Post a Comment for "Passing Python Variable To Sql"