Using Variables in SQL Statements in Python
When inserting data into an SQL table, it's essential to utilize parameters to pass variable values safely and effectively. Let's explore how to write variable names in Python code without including them as part of the query text.
Consider the following code:
cursor.execute("INSERT INTO table VALUES var1, var2, var3")
where var1 is an integer and var2 and var3 are strings. How can you avoid Python incorporating these variables into the query string?
Solution:
To achieve this, pass the variables as a tuple to the execute() method:
cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3))
Explanation:
Important Note:
The database API performs proper escaping and quoting of variables. Avoid using string formatting operators (%) for parameter substitution, as they:
The above is the detailed content of How Can I Safely Use Variables in Python SQL INSERT Statements?. For more information, please follow other related articles on the PHP Chinese website!