【发布时间】:2021-04-28 16:18:34
【问题描述】:
我尝试将 json api 的每个元素插入到我的 postgres 表中。
但我得到以下错误:
Traceback (most recent call last):
File "c:/Users/myname/Documents/repos/docker-playground/parse_json_to_postgres.py", line 20, in <module>
cursor.execute(f"INSERT into catfacts(data) VALUES ( {cat_fact} )")
psycopg2.errors.SyntaxError: syntax error at or near "{"
LINE 1: INSERT into catfacts(data) VALUES ( {'status': {'verified':...
^
我的 postgres 表:
CREATE TABLE cat_facts (
id serial NOT NULL PRIMARY KEY,
data jsonb NOT NULL
);
我的 Python 代码将数据插入到表中:
import requests, json, psycopg2
cat_facts_json = requests.get('https://cat-fact.herokuapp.com/facts').json
conn = psycopg2.connect(user="postgres",
password="password",
host="localhost",
port="5432",
database="postgres")
cursor = conn.cursor()
for cat_fact in cat_facts_json():
cursor.execute(f"INSERT into catfacts(data) VALUES ( \' {cat_fact} \' )")
API = https://cat-fact.herokuapp.com/facts
我想要达到的目标:
INSERT INTO cat_facts(data) VALUES ('{"status":{"verified":true,"sentCount":1},"type":"cat","deleted":false,"_id":"58e008800aac31001185ed07","user":"58e007480aac31001185ecef","text":"Wikipedia has a recording of a cat meowing, because why not?","__v":0,"source":"user","updatedAt":"2020-08-23T20:20:01.611Z","createdAt":"2018-03-06T21:20:03.505Z","used":false}');
INSERT INTO cat_facts(data) VALUES ('{"status":{"verified":true,"sentCount":1},"type":"cat","deleted":false,"_id":"58e008630aac31001185ed01","user":"58e007480aac31001185ecef","text":"When cats grimace, they are usually \"taste-scenting.\" They have an extra organ that, with some breathing control, allows the cats to taste-sense the air.","__v":0,"source":"user","updatedAt":"2020-08-23T20:20:01.611Z","createdAt":"2018-02-07T21:20:02.903Z","used":false},{"status":{"verified":true,"sentCount":1},"type":"cat","deleted":false,"_id":"58e00a090aac31001185ed16","user":"58e007480aac31001185ecef","text":"Cats make more than 100 different sounds whereas dogs make around 10.","__v":0,"source":"user","updatedAt":"2020-08-23T20:20:01.611Z","createdAt":"2018-02-11T21:20:03.745Z","used":false}');
....
【问题讨论】:
-
你看过这里的答案了吗? psycopg2 insert python dictionary as json
-
除了@StefanoFrazzetto 的帖子,请参阅Query parameters 了解为什么不应该使用格式化字符串。
-
@AdrianKlaver 我喜欢文档部分,它说:“永远,永远,永远不要使用 Python 字符串连接 (+) 或字符串参数插值 (%) 将变量传递给 SQL 查询字符串。甚至没有在枪口下。”
-
是的,我在 cat_facts_json() 中为 cat_fact 尝试过: cursor.execute("INSERT into catfacts(data) VALUES ( %s )" % json.dumps(cat_fact) ) 仍然无效同样的错误。
-
这对于 cat_facts_json() 中的 cat_fact: sql = "INSERT into catfacts(data) VALUES ( %s )" cursor.execute(sql,cat_fact) retuns:Traceback (最近一次调用最后一次):文件“c:/Users/user/Documents/repos/docker-playground/parse_json_to_postgres.py”,第 33 行,在
cursor.execute(sql,cat_fact) TypeError: dict is not a sequence
标签: python json postgresql rest