如何將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
相關文章
相關標籤/搜索