我正在编写一些 python 代码来对 redshift (postgres) SQL 数据库运行查询,但我遇到了一个问题,我无法从传递给的变量中去除周围的单引号查询。我正在尝试从列表中删除一些表。这是我的代码的基础知识:def func(table_list): drop_query = 'drop table if exists %s' #loaded from file table_name = table_list[0] #table_name = 'my_db.my_table' con=psycopg2.connect(dbname=DB, host=HOST, port=PORT, user=USER, password=PASS) cur=con.cursor() cur.execute(drop_query, (table_name, )) #this line is giving me trouble #cleanup statements for the connectiontable_list = ['my_db.my_table']当调用 func() 时,出现以下错误:syntax error at or near "'my_db.my_table'"LINE 1: drop table if exists 'my_db.my_table... ^有没有办法从列表项中删除周围的单引号?目前,我已经以错误的方式(认为是)完成了它并使用了字符串连接,但是我知道这基本上是在乞求 SQL 注入。
2 回答

慕田峪9158850
TA贡献1794条经验 获得超7个赞
这不是 psycopg2 的工作方式。您正在使用字符串运算符%s来替换字符串。这样做的原因是为了安全地标记您的字符串以避免 SQL 注入,psycopg2 处理其余部分。
您需要在查询进入执行语句之前对其进行修改。
drop_query = 'drop table if exists {}'.format(table_name)
但是,我警告您,不要让这些表名由外部来源创建,否则您将面临 SQL 注入的风险。
然而,新版本的 PSYCOPG2 允许类似的东西
http://initd.org/psycopg/docs/sql.html#module-psycopg2.sql
from psycopg2 import sql
cur.execute(
sql.SQL("insert into {} values (%s, %s)")
.format(sql.Identifier('my_table')),
[10, 20])

元芳怎么了
TA贡献1798条经验 获得超7个赞
我很确定这不是最好的方法,但您可以使用 replace() 函数删除特定符号或字符串的一部分。这应该有效:
cur.execute(drop_query, (table_name.replace("'", ""), ))
添加回答
举报
0/150
提交
取消