在将列表的字典插入到Postgres的表中时,如何包含'Null&;值?

人气:914 发布:2022-10-16 标签: python null postgresql psycopg2 insert-into

问题描述

我正在解析我的XML文件,并将它们存储到一个列表字典中,在那里我将使用心理拷贝g2将它们插入到posgres的表中。然而,并不是所有的行都被插入到表中(它只插入到列表中数量最少的值中)。以下是列表词典的摘录:

dict_songs = {'title' : ['Need You Now', 'GTFO'...], 'format': ['MP4', 'MP3'...], 'type' : ['Country Pop', 'R&B Pop'..], 'year': [2010,2018..]}

dict_movie = {'title' : ['Searching', 'Sidewalk of New York'...], 'format': ['DVD', 'Blue Ray'...], 'type' : ['Thriller', 'Romcom'..], 'year': [2018..]

当我计算词典中每个列表的长度时,发现并不是所有的列表都有相同的长度,例如:

for key, value in dict_songs.items():
    #print value
    print(key, len([item for item in value if item]))

# The result is:
title 300000
format 189700
type 227294
year 227094

标题将是歌曲表中的主键。当我将这本词典插入postgres时,它只显示了189700条记录,而不是300000条。我希望它是300000,并将NULL(无)值设置为Null。DICT_MOVICE也是如此

这是我用来将词典列表插入到表中的代码:

keys = ['title', 'format', 'type','year']
insert_statement = 'insert into song_table (%s) values %s'
for t in zip(*(dict_songs[key] for key in keys)):
   cur.execute(insert_statement3, (AsIs(','.join(keys)),t))
myConnection.commit()

你知道为什么要这么做,或者怎么做吗?谢谢!

推荐答案

我认为这里的问题在于您不知道None/NULL值在哪里。 把这些想象成清单:

dict_songs = {
  'title' : ['Need You Now', 'GTFO', 'Titletest']
  'type' : ['Country Pop', 'R&B Pop']
}

您的表的三个位置可能有空值,并且列表中没有可能提示正确的值的数据:

+ -------------+-------------+-------------+-------------+
| title        | type        | type        | type        |
+--------------+-------------+-------------+-------------+
| Need You Now | Country Pop | Country Pop | NULL        |
| GTFO         | R&B Pop     | NULL        | Country Pop |
| Jinglebells  | NULL        | R&B Pop     | R&B Pop     |
+--------------+-------------+-------------+-------------+

您的列表需要有None值,这样您就知道将Null放到数据库表中的什么位置。如下所示:

dict_songs = {
  'title' : ['Need You Now', 'GTFO', 'Titletest']
  'type' : ['Country Pop', None, 'R&B Pop']
}

810