Can I automatically create a table in PostgreSQL from a csv file with headers?

前端 未结 8 614
一整个雨季
一整个雨季 2020-11-30 00:22

I\'m running PostgreSQL 9.2.6 on OS X 10.6.8. I would like to import data from a CSV file with column headers into a database. I can do this with the COPY state

相关标签:
8条回答
  • 2020-11-30 00:58

    I am using csvsql to generate the table layout (it will automatically guess the format):

    head -n 20 table.csv | csvsql --no-constraints --tables table_name 
    

    And then I use \COPY in psql. That's for me the fastest way to import CSV file.

    You can also use sed with csvsql in order to get the desired datatype:

    head -n 20 table.csv | csvsql --no-constraints --tables table_name  | sed 's/DECIMAL/NUMERIC/' | sed 's/VARCHAR/TEXT/'
    
    0 讨论(0)
  • 2020-11-30 01:03

    Use sqlite as intermediate step.

    Steps:

    1. In the command prompt type: sqlite3
    2. In the sqlite3 CLI type: .mode csv
    3. .import my_csv.csv my_table
    4. .output my_table_sql.sql
    5. .dump my_table
    6. Finally execute that sql in your Postgresql
    0 讨论(0)
提交回复
热议问题