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

前端 未结 8 730
一整个雨季
一整个雨季 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/'
    

提交回复
热议问题