如何将CSV文件数据导入PostgreSQL表?

问题描述 投票:534回答:16

如何编写从CSV文件导入数据并填充表的存储过程?

postgresql csv postgresql-copy
16个回答
716
投票

看看这个short article


解决方案在这里解释:

创建你的表:

CREATE TABLE zip_codes 
(ZIP char(5), LATITUDE double precision, LONGITUDE double precision, 
CITY varchar, STATE char(2), COUNTY varchar, ZIP_CLASS varchar);

将CSV文件中的数据复制到表格中:

COPY zip_codes FROM '/path/to/csv/ZIP_CODES.txt' WITH (FORMAT csv);

6
投票

使用此SQL代码

    copy table_name(atribute1,attribute2,attribute3...)
    from 'E:\test.csv' delimiter ',' csv header

header关键字让DBMS知道csv文件有一个带属性的头

更多访问http://www.postgresqltutorial.com/import-csv-file-into-posgresql-table/


5
投票

恕我直言,最方便的方法是使用来自Import CSV data into postgresql, the comfortable way ;-)csvsql跟随“csvkit”,这是一个可以通过pip安装的python包。


0
投票

创建表并具有用于在csv文件中创建表的必需列。

  1. 打开postgres并右键单击要加载的目标表并选择导入并更新文件选项部分中的以下步骤
  2. 现在用文件名浏览你的文件
  3. 选择格式的csv
  4. 编码为ISO_8859_5

现在转到杂项。选项和检查标题,然后单击导入。


0
投票

如果您需要从文本/解析多行CSV导入的简单机制,您可以使用:

CREATE TABLE t   -- OR INSERT INTO tab(col_names)
AS
SELECT
   t.f[1] AS col1
  ,t.f[2]::int AS col2
  ,t.f[3]::date AS col3
  ,t.f[4] AS col4
FROM (
  SELECT regexp_split_to_array(l, ',') AS f
  FROM regexp_split_to_table(
$$a,1,2016-01-01,bbb
c,2,2018-01-01,ddd
e,3,2019-01-01,eee$$, '\n') AS l) t;

DBFiddle Demo


0
投票

在Python中,您可以使用此代码创建具有列名称的自动PostgreSQL表:

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)

它也相对较快,我可以在大约4分钟内导入超过330万行。


0
投票

我创建了一个小工具,将csv文件导入PostgreSQL超级简单,只是一个命令,它将创建和填充表,不幸的是,此刻所有字段自动创建使用TEXT类型

csv2pg users.csv -d ";" -H 192.168.99.100 -U postgres -B mydatabase

该工具可以在https://github.com/eduardonunesp/csv2pg上找到


0
投票

如何将CSV文件数据导入PostgreSQL表?

脚步:

  1. 需要在终端中连接postgresql数据库 psql -U postgres -h localhost
  2. 需要创建数据库 create database mydb;
  3. 需要创建用户 create user siva with password 'mypass';
  4. 连接数据库 \c mydb;
  5. 需要创建架构 create schema trip;
  6. 需要创建表 create table trip.test(VendorID int,passenger_count int,trip_distance decimal,RatecodeID int,store_and_fwd_flag varchar,PULocationID int,DOLocationID int,payment_type decimal,fare_amount decimal,extra decimal,mta_tax decimal,tip_amount decimal,tolls_amount int,improvement_surcharge decimal,total_amount );
  7. 将csv文件数据导入postgresql COPY trip.test(VendorID int,passenger_count int,trip_distance decimal,RatecodeID int,store_and_fwd_flag varchar,PULocationID int,DOLocationID int,payment_type decimal,fare_amount decimal,extra decimal,mta_tax decimal,tip_amount decimal,tolls_amount int,improvement_surcharge decimal,total_amount) FROM '/home/Documents/trip.csv' DELIMITER ',' CSV HEADER;
  8. 查找给定的表数据 select * from trip.test;

173
投票

如果您没有权限使用COPY(在数据库服务器上工作),则可以使用\copy(在db客户端中有效)。使用与Bozhidar Batsov相同的示例:

创建你的表:

CREATE TABLE zip_codes 
(ZIP char(5), LATITUDE double precision, LONGITUDE double precision, 
CITY varchar, STATE char(2), COUNTY varchar, ZIP_CLASS varchar);

将CSV文件中的数据复制到表格中:

\copy zip_codes FROM '/path/to/csv/ZIP_CODES.txt' DELIMITER ',' CSV

您还可以指定要读取的列:

\copy zip_codes(ZIP,CITY,STATE) FROM '/path/to/csv/ZIP_CODES.txt' DELIMITER ',' CSV

65
投票

一个快速的方法是使用Python pandas库(0.15或更高版本效果最佳)。这将处理为您创建列 - 尽管显然它对数据类型的选择可能不是您想要的。如果它不能完全按照您的要求进行操作,您可以始终使用作为模板生成的“创建表”代码。

这是一个简单的例子:

import pandas as pd
df = pd.read_csv('mypath.csv')
df.columns = [c.lower() for c in df.columns] #postgres doesn't like capitals or spaces

from sqlalchemy import create_engine
engine = create_engine('postgresql://username:password@localhost:5432/dbname')

df.to_sql("my_table_name", engine)

这里有一些代码向您展示如何设置各种选项:

# Set it so the raw sql output is logged
import logging
logging.basicConfig()
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)

df.to_sql("my_table_name2", 
          engine, 
          if_exists="append",  #options are ‘fail’, ‘replace’, ‘append’, default ‘fail’
          index=False, #Do not output the index of the dataframe
          dtype={'col1': sqlalchemy.types.NUMERIC,
                 'col2': sqlalchemy.types.String}) #Datatypes should be [sqlalchemy types][1]

28
投票

您还可以使用pgAdmin,它提供了一个GUI来执行导入。这在SO thread中显示。使用pgAdmin的优点是它也适用于远程数据库。

与之前的解决方案非常相似,您需要将数据库放在数据库中。每个人都有自己的解决方案,但我通常做的是在Excel中打开CSV,复制标题,在不同的工作表上粘贴特殊的转置,将相应的数据类型放在下一列,然后将其复制并粘贴到文本编辑器与适当的SQL表创建查询一起,如下所示:

CREATE TABLE my_table (
    /*paste data from Excel here for example ... */
    col_1 bigint,
    col_2 bigint,
    /* ... */
    col_n bigint 
)

20
投票

正如保罗所说,导入工作在pgAdmin:

右键单击表 - >导入

选择本地文件,格式和编码

这是一个德国pgAdmin GUI截图:

pgAdmin import GUI

你可以用DbVisualizer做类似的事情(我有许可证,不确定免费版)

右键单击表 - >导入表数据...

DbVisualizer import GUI


18
投票

此处的大多数其他解决方案都要求您提前/手动创建表。在某些情况下这可能不实用(例如,如果目标表中有很多列)。因此,下面的方法可能会派上用场。

提供csv文件的路径和列数,可以使用以下函数将表加载到名为target_table的临时表:

假设顶行具有列名。

create or replace function data.load_csv_file
(
    target_table text,
    csv_path text,
    col_count integer
)

returns void as $$

declare

iter integer; -- dummy integer to iterate columns with
col text; -- variable to keep the column name at each iteration
col_first text; -- first column name, e.g., top left corner on a csv file or spreadsheet

begin
    set schema 'your-schema';

    create table temp_table ();

    -- add just enough number of columns
    for iter in 1..col_count
    loop
        execute format('alter table temp_table add column col_%s text;', iter);
    end loop;

    -- copy the data from csv file
    execute format('copy temp_table from %L with delimiter '','' quote ''"'' csv ', csv_path);

    iter := 1;
    col_first := (select col_1 from temp_table limit 1);

    -- update the column names based on the first row which has the column names
    for col in execute format('select unnest(string_to_array(trim(temp_table::text, ''()''), '','')) from temp_table where col_1 = %L', col_first)
    loop
        execute format('alter table temp_table rename column col_%s to %s', iter, col);
        iter := iter + 1;
    end loop;

    -- delete the columns row
    execute format('delete from temp_table where %s = %L', col_first, col_first);

    -- change the temp table name to the name given as parameter, if not blank
    if length(target_table) > 0 then
        execute format('alter table temp_table rename to %I', target_table);
    end if;

end;

$$ language plpgsql;

16
投票
COPY table_name FROM 'path/to/data.csv' DELIMITER ',' CSV HEADER;

7
投票

PostgreSQL的个人经验,仍然在等待更快的方式。

1.如果文件存储在本地,则首先创建表骨架:

    drop table if exists ur_table;
    CREATE TABLE ur_table
    (
        id serial NOT NULL,
        log_id numeric, 
        proc_code numeric,
        date timestamp,
        qty int,
        name varchar,
        price money
    );
    COPY 
        ur_table(id, log_id, proc_code, date, qty, name, price)
    FROM '\path\xxx.csv' DELIMITER ',' CSV HEADER;

2.当\ path \ xxx.csv在服务器上时,postgreSQL没有访问服务器的权限,您必须通过内置的pgAdmin功能导入.csv文件。

右键单击表名称选择导入。

enter image description here

如果您仍有问题,请参阅本教程。 http://www.postgresqltutorial.com/import-csv-file-into-posgresql-table/


7
投票
  1. 先创建一个表
  2. 然后使用copy命令复制表详细信息:

copy table_name(C1,C2,C3 ....) 从'path to your csv file'delimiter','csv header;

谢谢

© www.soinside.com 2019 - 2024. All rights reserved.