Can not “COPY FROM” with Postgres & Python

旧巷老猫 提交于 2019-12-24 00:55:09

问题


As the topic, this is the code and there is no error message but data did not get insert. This is my code, and can anyone tell me what's wrong with it?

import psycopg2
import sys
import os
import glob 
import csv

#open the csv folder
dictfile='******'
os.chdir(dictfile)
total=[]
for file in glob.glob("*.csv"):
    total.append(file)
con = None
try: 
    con = psycopg2.connect(host='localhost',database='*****',user='postgres', password='*****') 
    cur = con.cursor()
    for i in range(0,1):   
        filename='/Users/Shared'+'/'+total[0]
        print filename
        #better move all files into shared folder
        x="copy public.crossref_sample from "+ "'"+filename+"'"+" DELIMITERS ',' CSV"
        print x
        cur.execute(x)  
except psycopg2.DatabaseError, e:
    print 'Error %s' % e    
    sys.exit(1) 
finally:
    if con:
        con.close()

回答1:


As alluded to by @a_horse_with_no_name, you're closing the PostgreSQL database connection, but you're not committing the transaction first.

psycopg2 opens a transaction for you if there isn't one already open. It expects you to commit this transaction when you've finished your work.

Unless you explicitly commit a transaction, closing the connection will rollback any work that's been done.

Try con.commit() after the last copy command.



来源:https://stackoverflow.com/questions/13868492/can-not-copy-from-with-postgres-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!