简体   繁体   English

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

[英]how to import csv data to postgres database using python

I am trying to import the data in my excel sheet to the postgresql database using python, and when i do that i get the following error.我正在尝试使用 python 将 excel 表中的数据导入 postgresql 数据库,当我这样做时,我得到以下错误。

i have already converted my excel to csv and then tried using the 'copy' statement to import the data to postgres database.我已经将我的 excel 转换为 csv,然后尝试使用“复制”语句将数据导入 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..."```

Judging by the error text ( missing data for column ), it seems like the number of columns in us_arrays table doesn't match the number of columns in your CSV file.从错误文本(列的missing data for column )来看, us_arrays表中的列数似乎与 CSV 文件中的列数不匹配。 You can also use columns keyword attribute when calling copy_from to specify the database table columns which should be populated from your file.您还可以在调用copy_from时使用columns关键字属性来指定应从文件中填充的数据库表列。 Read more about it here . 在此处阅读更多相关信息。

A common scenario would be having a database table with 3 columns, eg id , num , data and a CSV file with only 2 columns num and data .一个常见的场景是有一个包含 3 列的数据库表,例如idnumdata和一个只有 2 列numdata的 CSV 文件。 Without specifying columns , the copy_from function would import num from the CSV file into id database column, data into num , and there would be no data left to import into data database column.如果不指定columns ,则copy_from function 会将 CSV 文件中的num导入id数据库列,将data导入num ,并且将没有数据可以导入data数据库列。

Your question is tagged as Django, so I'll consider you want to import something linked to Model .您的问题被标记为 Django,所以我认为您要导入与Model链接的内容。

I give a detail explanation on how to speed up XL loading in this response Now, if performance is not an issue (your dataset is not too big, and do not have FKs), you can simply use Django Import Export我在此响应中详细解释了如何加快 XL 加载现在,如果性能不是问题(您的数据集不是太大,并且没有 FK),您可以简单地使用Django Import Export

Adding mixins to your Admin, you won't have to bother about file conversion and will give you diff when loading your file向您的管理员添加 mixins,您不必担心文件转换,并且会在加载文件时为您提供diff

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM