copy data from csv to postgresql using python

前端 未结 8 1172
遥遥无期
遥遥无期 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 04:03

    Use the copy_from cursor method

    f = open(r'C:\Users\n\Desktop\data.csv', 'r')
    cur.copy_from(f, temp_unicommerce_status, sep=',')
    f.close()
    

    The file must be passed as an object.

    Since you are coping from a csv file it is necessary to specify the separator as the default is a tab character

    0 讨论(0)
  • 2021-02-04 04:07

    I know this question has been answered, but here are my two cent. I am adding little more description:

    You can use cursor.copy_from method :

    First you have to create a table with same no of columns as your csv file.

    Example:

    My csv looks like this:

    Name,       age , college , id_no , country , state   , phone_no
    
    demo_name   22  , bdsu    , 1456  , demo_co , demo_da , 9894321_
    

    First create a table:

    import psycopg2
    from psycopg2 import Error
    
    connection = psycopg2.connect(user = "demo_user",
                                      password = "demo_pass",
                                      host = "127.0.0.1",
                                      port = "5432",
                                      database = "postgres")
    cursor = connection.cursor()
    
    
    create_table_query = '''CREATE TABLE data_set
    (Name  TEXT NOT NULL ,
    age  TEXT NOT NULL ,
    college  TEXT NOT NULL ,
    id_no TEXT NOT NULL ,
    country TEXT NOT NULL ,
    state TEXT NOT NULL ,
    phone_no TEXT NOT NULL);'''
    
    cursor.execute(create_table_query)
    connection.commit()
    

    Now you can simply use cursor.copy_from where you need three parameters :

    first file object , second table_name , third sep type
    

    you can copy now :

    f = open(r'final_data.csv', 'r')
    cursor.copy_from(f, 'data_set', sep=',')
    f.close()
    

    done

    0 讨论(0)
提交回复
热议问题