代码之家  ›  专栏  ›  技术社区  ›  Cap Lee

executemany函数的Python语法错误

  •  0
  • Cap Lee  · 技术社区  · 7 年前

    我试图用python将数据插入数据库,但查询中存在语法错误。我试图让代码获取一个列表,并能够将该列表添加到postgresql表的一行中。我找到了一些将列表添加到表中的方法,其中一些方法有“?”在里面。我不知道这意味着什么,也不知道为什么会导致错误。它给我的错误是:

    syntax error at or near ","
    LINE 1: INSERT INTO TestTable VALUES (?, ?, ?, ?, ?, ?, ?);
    

    这是我的密码。

    var_string = ', '.join('?' * len(items_list))
    query_string = 'INSERT INTO TestTable VALUES (%s);' % var_string
    cur.executemany(query_string, items_list)
    
    2 回复  |  直到 7 年前
        1
  •  0
  •   clemens    7 年前

    PyGreSQL的参数按格式、名称或位置进行描述:

    query_string = 'INSERT INTO TestTable VALUES (%(id)d, %(name)s, %(date)s)'
    cur.execute(query_string, dict(
        id = 1, name = 'Cap Lee', date = datetime.date.today()))
    

    query_string = 'INSERT INTO TestTable VALUES (%d, %s, %s)'
    cur.execute(query_string, (1, 'Cap Lee', datetime.date.today()))
    
        2
  •  0
  •   Cap Lee    7 年前

    好的,我找到了问题的答案。因此,我能够找到另一种方法将列表添加到我的表中。我首先对查询进行了硬编码,然后了解到“?”标记用于另一个框架,而不是postgresql。对于postgresql,我需要使用%s。我用''%1!''字符替换了问号,结果成功了。接下来我做的是修复并制作一个不太硬编码的版本。这是:

    items = [data] // items is the list we are trying to add to the db table
    copy_string = re.sub(r'([a-z])(?!$)', r'\1,', '%s' * len(items)) // len of items list is 7
    final_string = re.sub(r'(?<=[.,])(?=[^\s])', r' ', copy_string)
    query_string = 'INSERT INTO TestTable VALUES (%s);' % final_string
    cur.execute(query_string, items)
    

    查询字符串的输出应如下所示:

    INSERT INTO TestTable VALUES(%s, %s, %s, %s, %s, %s, %s);
    

    每个''%1!''字符从列表中获取一个值。代码接收一个列表并将它们添加到db表中的一行中。