我正在做一个抓取项目,我正在努力将数据插入数据库。
我的数据库有三列:id, post 和 author 抓取的数据存储在两个列表中。第一个是列表帖子,第二个是作者。两者总是相同的长度,因为没有没有内容的文章或没有作者的文章。
我已经尝试过 this 中提供的解决方案问题,但我得到了这个错误:
Traceback (most recent call last):
File "scrape.py", line 69, in <module>
cur.execute("INSERT into posts(id, post, author) VALUES (%s, %s, %s)", authors)
TypeError: not all arguments converted during string formatting
我的列表是这样的:
author = [n1, n2, n3 ... n45]
posts = [n1, n2, n3 ... n45]
我想像这样将它们插入数据库:
ID | Post | Author
---|------|--------
1 | Text | Author
2 | Text | Author
稍后我需要从帖子列中的值中提取统计信息。确切地说是它们出现的次数和次数,但我想它符合另一个问题的条件。
最佳答案
您尝试将作者列表插入到帖子表中?这不太合理。
你肯定在找这样的东西
data = [(1, 'post', 'author'), (2, 'post', 'author')]
for d in data:
cur.execute("INSERT into posts(id, post, author) VALUES (%s, %s, %s)", d)
此外 id 值通常是整数,但您似乎将其格式化为字符串
如果您想保留单个列表,请查看 zip(posts, authors)
的结果
关于python - 将 python 列表插入 PostgreSQL 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44485127/