【问题标题】:psycopg2 pass arguments to SQL Programming Errorpsycopg2 将参数传递给 SQL 编程错误
【发布时间】:2023-04-06 17:35:01
【问题描述】:

我尝试按照 docs 中描述的方式传递参数,但出现以下错误: 文件“slug_word.py”,第 100 行,在 get_col cur.execute("从 %s 中选择 %s" , data ) psycopg2.ProgrammingError:“E'catalog_category'”处或附近的语法错误 第 1 行:从 E'catalog_category' 中选择 E'slug'

以下是我的代码摘录:

def get_col(cxn, table, col):
    "fetch a column"
    cur = cxn.cursor()
    data = (col, table)
    cur.execute("select %s from %s" , data ) 
    rows = cur.fetchall()
    return rows

def main():

    cxn = connect('galleria')
    table = 'catalog_category'
    col = 'slug'
    rows = get_col(cxn, table, col)

【问题讨论】:

    标签: parameters psycopg2


    【解决方案1】:

    通过重新阅读有关此问题的帖子Steve Holden,我发现在我的代码中参数必须以python方式传递:

     ..."select %s from %s" % data ) 
    

    只有进入数据库的“真实”数据必须使用 psycopg2 参数方法,而不是表和列名之类的东西。 不幸的是,数据和表名的混合不起作用。

    【讨论】:

      【解决方案2】:

      你可以使用AsIs psycopg2 函数:

      Adapter 符合 ISQLQuote 协议,该协议适用于其对象 字符串表示已经作为 SQL 表示有效。

      import psycopg2
      from psycopg2.extensions import AsIs
      
      def get_col(conn, table, col):
          '''Fetch a column'''
      
          QUERY = 'SELECT %(col)s from %(table)s'
          data = {'col': AsIs(col), 'table': AsIs(table)}
          with conn.cursor() as cursor:
              cursor.execute(QUERY, data)
              rows = cursor.fetchall()        
          return rows
      

      【讨论】:

        猜你喜欢
        • 2012-01-30
        • 2014-06-16
        • 1970-01-01
        • 2013-07-30
        • 1970-01-01
        • 2015-02-02
        • 2017-08-17
        • 1970-01-01
        相关资源
        最近更新 更多