我正嘗試使用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的代碼,我們怎麼知道它出錯了? –