[英]Insert into table values from a dictionary in a Postgresql database
I have a dictionary in python that I created from a JSON file. 我有一个从JSON文件创建的python字典。 Now, I need to pass its values to insert into a postgresql database.
现在,我需要传递其值以插入到PostgreSQL数据库中。
dictionary 字典
if(i['trailers']):
a = [
{'url': i['images'][0]['url'], 'type': i['images'][0]['type']},
{'url': i['images'][1]['url'], 'type': i['images'][1]['type']},
{'url': i['trailers'][0]['url'], 'type': 'Trailer'},
{'url': i['trailers'][1]['url'], 'type': 'Trailer'},
]
else:
a = [
{'url': i['images'][0]['url'], 'type': i['images'][0]['type']},
{'url': i['images'][1]['url'], 'type': i['images'][1]['type']},
]
length = len(a)
Here, I created the dictionary. 在这里,我创建了字典。 If there is anything inside the
trailer
it goes A, else it goes B. In the B case, trailers
doesn't exists. 如果
trailer
内有东西,它就会变为A,否则便变为B。在B情况下, trailers
不存在。 Then I get the length of the dictionary. 然后我得到了字典的长度。
Now, I will try to insert these elements into the table media, that depends on movies. 现在,我将尝试将这些元素插入依赖于电影的表媒体中。 Their relation is movie(1):media(n).
它们的关系是movie(1):media(n)。
INSERT INTO media 插入媒体
for x in range(length):
query = ("""INSERT INTO media VALUES (%s, %s, %(url)s, %(type)s);""")
data = (media_id, media_movie_id)
cur.execute(query, data)
conn.commit()
media_id += 1
Here is what I'm trying to do. 这就是我想要做的。 Since movie can have many media, I'll create a for to move through all the elements and inserting them in the table.
由于电影可以包含多种媒体,因此我将创建一个for来遍历所有元素并将其插入表格中。 With their id being incremented.
随着他们的身份证增加。
The problem is, I don't know how to do this quiet right in Python, since I always create a query and a data and then cur.execute
it and the example that I got, was a entire dictionary being used, without any other kind of value. 问题是,我不知道如何在Python中做到这一点,因为我总是创建一个查询和一个数据,然后执行
cur.execute
它,而我得到的示例是使用了整个字典,而没有其他任何字典一种价值。
So, if anyone have this kind of problem, the solution is simple, actually. 因此,如果有人遇到这种问题,实际上解决方案很简单。
I remade my dict in something like this: 我用以下方法重做了我的字典:
i['trailers'] = i.get('trailers') or []
dictionary = [{'url': x['url'], 'type': x['type']} for x in i['images'] + i['trailers']]
This solution was made by @minboost here 这个解决方案是由@minboost 在这里提出的
Then, for the insertion, is something like that: 然后,对于插入,是这样的:
for i, dic in enumerate(dictionary):
query = ("""
INSERT INTO media (id, movie_id, url, type)
VALUES (%s, %s, %s, %s);
"""
)
data = (media_id, media_movie_id, dictionary[i]['url'], dictionary[i]['type'])
cur.execute (query, data)
conn.commit()
All working perfectly. 一切正常。 :)
:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.