将列表写入列

时间:2017-12-14 02:44:59

标签: python-3.x postgresql

数据以

格式显示
tags_list = [
    ['foo'],
    ['foo', 'boo', 'goo'],
    ['boo', 'zoo']
]

如何填写专栏tags TEXT[]? 我试图做一些像

这样的事情
cursor.executemany("""INSERT INTO tags_table VALUES (%s);""", tags_list)

但它会引发异常not all arguments converted during string formatting

输入数据格式当然可以通过任何方式进行修改。

更新

好的,我这样做:

for tags in tags_list:
    tags_literal = '{"' + '","'.join(tags) + '"}'
    cursor.execute("""INSERT INTO tags_data VALUES (%s);""", (tags_literal,))

但表中的行如下所示:

(['foo'],)
(['foo', 'boo', 'goo'],)
(['boo', 'zoo'],)

虽然我期待着:

{'foo'}
{'foo', 'boo', 'goo'}
{'boo', 'zoo'}

任何想法? :)

3 个答案:

答案 0 :(得分:2)

按照我的阅读here,以下内容应该有效:

for tags in tags_list:
    tags_with_quotes = ['"' + tag + '"' for tag in tags]
    tags_literal = "{" + ",".join(tags_with_quotes) + "}"
    cursor.execute("INSERT INTO tags_table VALUES (%s);", (tags_literal,))

答案 1 :(得分:2)

如果使用参数列表列表参数化executemany()

  • 所有这些内部列表必须具有相同的确切长度
  • 参数的数量需要等于占位符的数量

换句话说,在当前状态下它不起作用,因为您的内部列表具有不同的长度,并且查询中只有一个占位符。

使所有内部列表包含单项元组应该使它工作:

tags_list = [
    (['foo'], ),
    (['foo', 'boo', 'goo'], ),
    (['boo', 'zoo'], )
]
cursor.executemany("""INSERT INTO tags_table VALUES (%s);""", tags_list)

答案 2 :(得分:1)

根据此评论:“如果可能的话,最好只对整个列表列表执行一次查询”

是的,这是可能的,但您需要手工构建insert语句。像这样:

tags_list = [['foo'], ['foo', 'boo', 'goo'], ['boo', 'zoo']]

# I am not Python guru, probably there is more elegant solution

s = 'insert into tags_table values' + ','.join(['(%s)'] * len(tags_list))
print s

# Output: insert into tags_table values(%s),(%s),(%s)

cur.execute(s, tags_list)

它应该如何使用循环:

for tags in tags_list:
    cursor.execute("""INSERT INTO tags_data VALUES (%s);""", (tags,))