如何使用python将csv数据导入Postgres数据库

问题描述 投票:0回答:2

我正在尝试使用python将excel工作表中的数据导入到postgresql数据库,当我这样做时,出现以下错误。

我已经将我的excel转换为csv,然后尝试使用'copy'语句将数据导入到postgres数据库。

import psycopg2

conn = psycopg2.connect("host=localhost dbname=djangotest user=postgres password=*******")
cur = conn.cursor()

with open('C:\\Users\\********\\Desktop\\excelsheet.csv', 'r') as f:
    next(f) # Skip the header row.
    cur.copy_from(f, 'us_arrays', sep=',')

conn.commit()
psycopg2.errors.BadCopyFileFormat: missing data for column "ip_address_or_service_machine"
CONTEXT:  COPY us_arrays, line 1: "(CMDB)",.Device Type,.Frame or Data Tier,.Corp Device,.Encrypt Enabled,.Dedicated Device,".IP Addres..."```
python django excel postgresql pycharm
2个回答
0
投票

根据错误文本(missing data for column)判断,似乎us_arrays表中的列数与CSV文件中的列数不匹配。调用columns来指定应从文件填充的数据库表列时,也可以使用copy_from关键字属性。进一步了解here

常见的情况是,数据库表包含3列,例如idnumdata和CSV文件只有两列numdata。如果不指定columns,则copy_from函数会将CSV文件中的num导入到id数据库列中,将data导入到num中,并且将没有数据可导入到data数据库列中。


0
投票

您的问题被标记为Django,所以我认为您想导入链接到Model的内容。

我详细说明了如何在this response中加快XL加载速度现在,如果性能不是问题(您的数据集不是太大,并且没有FK),则可以简单地使用Django Import Export

向管理员添加mixins,您不必担心文件转换,并且在加载文件时会给您diff

© www.soinside.com 2019 - 2024. All rights reserved.