copy data from csv to postgresql using python

前端 未结 8 1180
遥遥无期
遥遥无期 2021-02-04 03:32

I am on windows 7 64 bit. I have a csv file \'data.csv\'. I want to import data to a postgresql table \'temp_unicommerce_status\' via a python script.

My Script is:

8条回答
  •  南方客
    南方客 (楼主)
    2021-02-04 03:56

    #sample of code that worked for me
    
    import psycopg2 #import the postgres library
    
    #connect to the database
    conn = psycopg2.connect(host='localhost',
                           dbname='database1',
                           user='postgres',
                           password='****',
                           port='****')  
    #create a cursor object 
    #cursor object is used to interact with the database
    cur = conn.cursor()
    
    #create table with same headers as csv file
    cur.execute("CREATE TABLE IF NOT EXISTS test(**** text, **** float, **** float, **** 
    text)")
    
    #open the csv file using python standard file I/O
    #copy file into the table just created 
    with open('******.csv', 'r') as f:
    next(f) # Skip the header row.
        #f , , Comma-Seperated
        cur.copy_from(f, '****', sep=',')
        #Commit Changes
        conn.commit()
        #Close connection
        conn.close()
    
    
    f.close()
    

提交回复
热议问题