【问题标题】:Psycopg2 query with variable number of parameters throws syntax error具有可变数量参数的 Psycopg2 查询引发语法错误
【发布时间】:2014-02-27 23:38:58
【问题描述】:

我编写了一个 Python 函数来获取列表(可变长度)并将其插入到表中(与每个列表中的值相同的列数):

ps.cur = psycopg_cursor

def load_lists(list_of_lists, table):
    # Get number of columns in table
    sql = """
          SELECT column_name FROM information_schema.columns
          WHERE table_schema = 'public'
          AND table_name = '{}'
          """.format(table)
    ps.cur.execute(sql)
    columns_list = [i[0] for i in ps.cur.fetchall()]
    # Insert list of lists into table
    columns = '(' + ','.join(columns_list) + ')'
    parameters = '(' + ','.join(['%%s' for i in columns_list]) + ')'
    for i in list_of_lists:
        sql = """
              INSERT INTO {} {}
              VALUES {}
              """.format(table, columns, parameters)
        values = tuple([j for j in i])
        ps.cur.execute(sql, values)

我得到以下回溯尝试执行该功能:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "psyco.py", line 24, in load_lists
    ps.cur.execute(sql, values)
psycopg2.ProgrammingError: syntax error at or near "%"
LINE 3:               VALUES (%s,%s,%s,%s,%s)
                              ^

似乎 Psycopg2 无法将我的变量绑定到 %s 参数,但我不知道为什么。非常感谢任何帮助或想法!

【问题讨论】:

    标签: python postgresql psycopg2


    【解决方案1】:

    在为我的查询构建参数标记时,我只需要在每个 's' 前面加一个 %。这有点令人困惑,因为 Python 中的旧字符串格式化方法也使用 % 符号,但与 Psycopg2 不同。请参阅下面的工作代码(仅更改“参数”变量):

    ps.cur = psycopg_cursor

    def load_lists(list_of_lists, table):
        # Get number of columns in table
        sql = """
              SELECT column_name FROM information_schema.columns
              WHERE table_schema = 'public'
              AND table_name = '{}'
              """.format(table)
        ps.cur.execute(sql)
        columns_list = [i[0] for i in ps.cur.fetchall()]
        # Insert list of lists into table
        columns = '(' + ','.join(columns_list) + ')'
        parameters = '(' + ','.join(['%s' for i in columns_list]) + ')' # <--- THIS LINE
        for i in list_of_lists:
            sql = """
                  INSERT INTO {} {}
                  VALUES {}
                  """.format(table, columns, parameters)
            values = tuple([j for j in i])
            ps.cur.execute(sql, values)
    

    【讨论】:

      猜你喜欢
      • 2012-03-10
      • 1970-01-01
      • 2014-07-08
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-11
      相关资源
      最近更新 更多