简体   繁体   English

在 python 中使用 psycopg2 在参数化查询中输入字符串作为参数时出现问题

[英]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:作为数据库编程的初学者,我想问:

  1. How can I get rid of those quotations from the query?我怎样才能摆脱查询中的那些引用? Or do I make any mistake here?或者我在这里犯了什么错误?
  2. Is this a good practise in preventing SQL injections?这是防止 SQL 注射的好习惯吗? Or is it a good practise in writing a parameterized query like this?还是像这样编写参数化查询是一种好习惯?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM