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

如何编写一个存储过程,该存储过程从CSV文件导入数据并填充表? sql


#1楼

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

可是,与以前的解决方案很是类似,您将须要在数据库中拥有表。 每一个人都有本身的解决方案,但我一般要作的是在Excel中打开CSV,复制标题,将带有换位符的特殊内容粘贴在不一样的工做表上,将相应的数据类型放在下一列中,而后将其复制并粘贴到文本编辑器中加上适当的SQL表建立查询,以下所示: api

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

#2楼

一种快速的方法是使用Python pandas库(版本0.15或更高版本效果最好)。 这将为您建立列-尽管显然对数据类型所作的选择可能不是您想要的。 若是不能彻底知足您的要求,则能够始终使用做为模板生成的“建立表”代码。 服务器

这是一个简单的例子: app

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]

#3楼

看一下这篇简短的文章ide


解决方案的解释以下: 函数

建立表: oop

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

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

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

#4楼

这里的大多数其余解决方案要求您事先/手动建立表。 在某些状况下(例如,若是目标表中有不少列),这可能不切实际。 所以,如下方法可能会派上用场。

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

#5楼

若是您无权使用COPY (在db服务器上工做),则能够改用\\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
相关文章
相关标签/搜索