Variable Binding in SQL Statements Using Python
In Python, it's essential to pass variables into SQL statements without including them as part of the query string. This prevents SQL injection attacks and ensures proper parameter handling.
To achieve this, use the cursor.execute() method with placeholders (e.g., %s for strings, %d for integers, and '%f' for floating-point values) to represent the variables.
cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3))
Note that the parameters to the execute() method must be a tuple, even if you're passing a single value. To indicate a single parameter, use a tuple with a trailing comma:
cursor.execute("INSERT INTO table VALUES (%s)", (var1,))
The database API handles the proper escaping and quoting of variables. Avoid using the string formatting operator (%) as it does not perform any escaping or quoting, leaving the application vulnerable to attacks. Additionally, it's important to use prepared statements (like the one shown here) instead of concatenating strings to build the SQL statement, as it improves both security and performance.
The above is the detailed content of How Can I Safely Bind Variables in SQL Statements Using Python?. For more information, please follow other related articles on the PHP Chinese website!