Python:如何从列表项中删除单引号

我正在编写一些 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 注入。


米脂
浏览 357回答 2
2回答

慕田峪9158850

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

元芳怎么了

我很确定这不是最好的方法,但您可以使用 replace() 函数删除特定符号或字符串的一部分。这应该有效:cur.execute(drop_query, (table_name.replace("'", ""), ))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python