[英]Issues when input strings as parameter in parameterized query with psycopg2 in python
Now I am trying to read sth from the database with parameterized query.现在我正在尝试使用参数化查询从数据库中读取某些内容。 To avoid SQL injection, I wrote the code as follows:
为了避免 SQL 注入,我写了如下代码:
param = 'Peter'
column_name = 'employee.name'
table_name = 'employee'
param_query = 'SELECT * FROM %s WHERE %s = %s'
# Return outcome
cur.execute(param_query, [table_name, column_name, param])
outcome = cur.fetchall()
print(outcome)
And I got the following error:我收到以下错误:
psycopg2.errors.SyntaxError: syntax error at or near "'employee'"
LINE 1: SELECT * FROM 'employee' WHERE 'employee.name' = 'Peter'
As a beginner in database programming, I want to ask:作为数据库编程的初学者,我想问:
Thank you for your help in advance!提前谢谢你的帮助!
Problem solved with the followings:问题通过以下方式解决:
param = 'Peter'.lower()
column_name = AsIs('employee.name')
table_name = AsIs('employee')
param_query = 'SELECT * FROM %s WHERE %s = %s'
# Return outcome
cur.execute(param_query, [table_name, column_name, param])
outcome = cur.fetchall()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.