How to import CSV file data into a PostgreSQL table?

前端 未结 19 2762
再見小時候
再見小時候 2020-11-22 02:14

How can I write a stored procedure that imports data from a CSV file and populates the table?

19条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 03:15

    In Python, you can use this code for automatic PostgreSQL table creation with column names:

    import pandas, csv
    
    from io import StringIO
    from sqlalchemy import create_engine
    
    def psql_insert_copy(table, conn, keys, data_iter):
        dbapi_conn = conn.connection
        with dbapi_conn.cursor() as cur:
            s_buf = StringIO()
            writer = csv.writer(s_buf)
            writer.writerows(data_iter)
            s_buf.seek(0)
            columns = ', '.join('"{}"'.format(k) for k in keys)
            if table.schema:
                table_name = '{}.{}'.format(table.schema, table.name)
            else:
                table_name = table.name
            sql = 'COPY {} ({}) FROM STDIN WITH CSV'.format(table_name, columns)
            cur.copy_expert(sql=sql, file=s_buf)
    
    engine = create_engine('postgresql://user:password@localhost:5432/my_db')
    
    df = pandas.read_csv("my.csv")
    df.to_sql('my_table', engine, schema='my_schema', method=psql_insert_copy)
    

    It's also relatively fast, I can import more than 3.3 million rows in about 4 minutes.

提交回复
热议问题