[英]Python: How to remove single quotes from list item
我正在处理一些 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 connection
table_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 注入。
这不是psycopg2的工作方式。 您正在使用字符串运算符%s
替换为字符串。 这样做的原因是为了安全地对字符串进行标记,以避免SQL注入,而psycopg2处理其余部分。
您需要在查询进入execute语句之前对其进行修改。
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])
我敢肯定这不是最好的方法,但是您可以使用replace()函数删除特定的符号或字符串的一部分。 这应该工作:
cur.execute(drop_query, (table_name.replace("'", ""), ))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.