copy from方法

最近更新时间: 2024-10-17 17:10:00

#coding=utf-8
#!/usr/bin/python
import psycopg2
try:
    conn = psycopg2.connect(database="postgres", user="tbase", password="", host="172.16.0.29", port="15432")
    print "连接数据库成功"    
    cur = conn.cursor()
    filename = "/data/tbase/tbase.txt"
    cols = ('id','nickname')
    tablename="public.tbase"
    cur.copy_from(file=open(filename),table=tablename,columns=cols,sep=',')
    conn.commit()
    print "导入数据成功"
    conn.close()
except psycopg2.Error,msg:
    print "操作数据库出库 %s" %(msg.args[0])

运行

[tbase@VM_0_29_centos python]$ python copy_from.py 
#连接数据库成功
#导入数据成功