python-3.x - 将列表写入列

标签 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'}

有什么想法吗? :)

最佳答案

按照我阅读的内容进行操作 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,))

关于python-3.x - 将列表写入列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47805085/

相关文章:

python Reportlab 段落中同一行中的两个项目

python-3.x - 加速 Python 程序(自适应中值滤波器)

python - 如何在Python中对列表列表中的元素进行分组?

python - 什么可能导致此错误: FileNotFoundError: [Errno 2] No such file or directory

sql - 缺少列结果(应该很容易修复)

sql - PostgreSQL - 如何抑制查询语句消息

ruby - 在 postgres Rails-4 中查询 Json 数据类型

python - 返回元素后如何正确关闭 Selenium webdriver?

sql - 使用 PostgreSQL ECPG 插入数组

sql - 将新值映射到 sql 查询的有效方法(即 4 列,每列具有相同的凭据)