【问题标题】:Insert into table values from a dictionary in a Postgresql database从 Postgresql 数据库的字典中插入表值
【发布时间】:2018-12-27 20:28:25
【问题描述】:

我有一个从 JSON 文件创建的 Python 字典。现在,我需要传递它的值以插入到 postgresql 数据库中。

字典

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)

在这里,我创建了字典。如果trailer 中有任何内容,则为 A,否则为 B。在 B 的情况下,trailers 不存在。然后我得到字典的长度。

现在,我将尝试将这些元素插入到表格媒体中,这取决于电影。它们的关系是movie(1):media(n)。

插入媒体

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

这就是我想要做的。由于电影可以有许多媒体,我将创建一个 for 来移动所有元素并将它们插入到表格中。随着他们的 id 递增。

问题是,我不知道如何在 Python 中安静地做到这一点,因为我总是创建一个查询和一个数据,然后 cur.execute 它和我得到的示例是使用整个字典,没有任何其他类型的价值。

【问题讨论】:

    标签: python postgresql


    【解决方案1】:

    所以,如果有人遇到这种问题,其实解决方法很简单。

    我用这样的方式重新制作了我的字典:

    i['trailers'] = i.get('trailers') or []
    dictionary = [{'url': x['url'], 'type': x['type']} for x in i['images'] + i['trailers']]
    

    此解决方案由@minboost here提出

    然后,对于插入,是这样的:

    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()
    

    一切正常。 :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-03
      相关资源
      最近更新 更多