python - 向 postgres 表中插入一个列表

标签 python postgresql psycopg2

我想通过 Python 将值列表插入到 Postgres 表中:

值在列表中说:

new=
[
    [gold, dresden, 1000, 24],
    [silver, Cologne, 600, 42],
    [gold, Aachen, 3000, 25]
]

并且已经在 Postgres 中创建了带有标题的表。如何插入?

db.execute("INSERT INTO B4_O (position, city, amount, score) VALUES (%s,%s,%s)", new)
db.commit

但这给了我错误:

not all arguments converted during string formatting

最佳答案

使用psycopg2.extras.execute_values() :

new = [
    ['gold', 'dresden', 1000, 24],
    ['silver', 'Cologne', 600, 42],
    ['gold', 'Aachen', 3000, 25]
]

from psycopg2.extras import execute_values

execute_values(db, "INSERT INTO B4_O (position, city, amount, score) VALUES %s", new)

关于python - 向 postgres 表中插入一个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51460590/

相关文章:

python - 从 AWS Python lambda 函数返回 html 页面

python - 如何用 Python 将字典写入 Excel

python - 为什么 aptitude 没有正确安装 python-mysqldb? (错误 : No module named MySQLdb )

xml - PostgreSQL 8.4 XML、XSLT 和 XPath 可能性/文档

postgresql - Heroku Postgres - 突然出现错误

sql - `lock_timeout` 是 Postgres CREATE INDEX CONCURRENTLY 所必需的吗

Python 3.8 脚本在获取数据库连接(psycopg2 和多处理)时卡住 - Windows 7

python - 使用 SQLAlchemy 和 Mapped 创建表时指定时间戳列类型提示

python - 使用 python 插入 Postgres DB 列

python - 组合函数和功能模块