我正尝试使用Django将csv文件导入到postgres DB中。使用Django将CSV文件导入到postgres中
我尝试以下功能:
import os
from django.db import models
import psycopg2
from postgres_copy import CopyMapping
host = 'localhost'
port = '5432'
dbname = 'sellerhub'
username = 'postgres'
password = 'postgres'
class Reports:
def __init__(self):
global host, port, dbname, username, password
try:
self.db_conn = psycopg2.connect("host=%s port=%s dbname=%s user=%s password=%s" %(host, port, dbname, username, password))
except psycopg2.OperationalError:
print "Database Not Found Or the Credentials are wrong."
self.cur = self.db_conn.cursor()
def saveUploadedInventory(self, inventory_file):
#print "Inventory File"
with open('uploaded_inventory_sheet.csv','wb+') as destination:
for chunk in inventory_file.chunks():
destination.write(chunk)
#print "Inventory Saved."
copy_sql = """copy fk_invent_temp from stdin WITH CSV HEADER DELIMITER as ',' """
#print "query created"
with open('uploaded_inventory_sheet.csv','r') as pmt_file:
self.cur.copy_expert(sql=copy_sql, file=pmt_file)
#print "file uploades"
os.system('rm uploaded_inventory_sheet.csv')
#print "removes file"
和setting.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'sellerhub',
'USER': 'postgres',
'PASSWORD': 'postgres',
'HOST': 'localhost',
'PORT': '5432',
}
}
这个功能是没有错误完全地执行,
但在fk_invent表中没有数据。
如果我使用成功上传的PGAdmin3 UI直接导入该文件。 请问任何人可以告诉我做错了什么?
有太多的信息缺失。这是什么类的方法?什么是'self.cur'和'self.cur.copy_expert'? –
cur是从数据库和复制专家的连接是为了复制数据库 –
但是没有看到copy_expert的代码,我们怎么知道它出错了? –