How to put a parameterized sql query into a variable and then execute in Python?

I understand that the correct way to format a SQL query in Python is:

cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", var1, var2, var3)

to prevent sql invasion. My question is, is there a way to put the request into a variable and then execute it? I tried the example below, but got an error. Can this be done?

sql="INSERT INTO table VALUES (%s, %s, %s)", var1, var2, var3
cursor.execute(sql)
+7
source share
3 answers

Here is the call signature for cursor.execute:

Definition: cursor.execute(self, query, args=None)

    query -- string, query to execute on server
    args -- optional sequence or mapping, parameters to use with query.

Thus, execution expects no more than 3 arguments (arguments are optional). If arguments are given, it is expected to be a sequence. So

sql_and_params = "INSERT INTO table VALUES (%s, %s, %s)", var1, var2, var3
cursor.execute(*sql_and_params)

will not work because

cursor.execute(*sql_and_params)

extends the tuple sql_and_params by 4 arguments (and only 3 are executed again).

sql_and_params = "INSERT INTO table VALUES (%s, %s, %s)", var1, var2, var3

cursor.execute:

cursor.execute(sql_and_params[0],sql_and_params[1:])

, :

sql = "INSERT INTO table VALUES (%s, %s, %s)"
args= var1, var2, var3
cursor.execute(sql, args)
+14

.

sql_and_params = "INSERT INTO table VALUES (%s, %s, %s)", var1, var2, var3
cursor.execute(*sql_and_params)

, , .

+4

:

sql="INSERT INTO table VALUES (%s, %s, %s)"
cursor.execute(sql, (var1, var2, var3))

But I'm not sure if this is what you are looking for. It depends on whether you want the values ​​as part of the variable or not. If so, Ants Aasma's answer is probably correct. But beware of Bobby Tables .

0
source

All Articles