首页 文章

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

提问于
浏览
494

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

13 回答

  • 19

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

    右键单击表 - >导入

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

    这是一个德国pgAdmin GUI截图:

    pgAdmin import GUI

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

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

    DbVisualizer import GUI

  • 28

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

  • 690
    • 先创建一个表

    • 然后使用copy命令复制表格详细信息:

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

    谢谢

  • 4

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

    • 打开postgres并右键单击要加载的目标表并选择导入并更新 file options 部分中的以下步骤

    • 现在以文件名浏览您的文件

    • 选择格式的csv

    • 编码为ISO_8859_5

    现在转到 Misc. options 并检查 Headers 并单击导入 .

  • 0

    看看这个short article .


    解决方案在这里解释:

    Create your table:

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

    Copy data from your CSV file to the table:

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

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

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

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

    如果您需要从文本/解析多行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

  • 61

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

    1. Create table skeleton first if the file is stored locally:

    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. When the \path\xxx.csv is on the server, postgreSQL doesn't have the permission to access the server, you will have to import the .csv file through the pgAdmin built in functionality.

    右键单击表名选择导入 .

    enter image description here

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

  • 17
    COPY table_name FROM 'path/to/data.csv' DELIMITER ',' CSV HEADER;
    
  • 5

    一个快速的方法是使用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]
    
  • 0

    使用此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/

  • 6

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

    提供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;
    
  • 1

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

    Create your table:

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

    Copy data from your CSV file to the table:

    \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
    

相关问题