Programing

CSV 파일 데이터를 PostgreSQL 테이블로 가져 오는 방법은 무엇입니까?

lottogame 2020. 10. 4. 10:14
반응형

CSV 파일 데이터를 PostgreSQL 테이블로 가져 오는 방법은 무엇입니까?


CSV 파일에서 데이터를 가져와 테이블을 채우는 저장 프로 시저를 작성하려면 어떻게해야합니까?


짧은 기사를보십시오 .


여기에서 풀이 :

테이블 만들기 :

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);

사용 권한이없는 경우 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

이를 수행하는 한 가지 빠른 방법은 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]

가져 오기를 수행하는 GUI를 제공하는 pgAdmin을 사용할 수도 있습니다. SO 스레드에 표시 됩니다. pgAdmin 사용의 장점은 원격 데이터베이스에서도 작동한다는 것입니다.

하지만 이전 솔루션과 마찬가지로 데이터베이스에 이미 테이블이 있어야합니다. 각 사람은 자신의 솔루션을 가지고 있지만 일반적으로 Excel에서 CSV를 열고 머리글을 복사하고 다른 워크 시트에 전치하여 특수 붙여 넣기 한 다음 해당 데이터 유형을 다음 열에 배치 한 다음 복사하여 텍스트 편집기에 붙여 넣습니다. 다음과 같은 적절한 SQL 테이블 생성 쿼리와 함께 :

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

Paul이 언급했듯이 import는 pgAdmin에서 작동합니다.

테이블을 마우스 오른쪽 버튼으로 클릭-> 가져 오기

로컬 파일, 형식 및 코딩 선택

다음은 독일어 pgAdmin GUI 스크린 샷입니다.

pgAdmin import GUI

DbVisualizer로 할 수있는 것과 유사한 작업 (라이센스가 있지만 무료 버전에 대해 잘 모르겠습니다)

테이블을 마우스 오른쪽 버튼으로 클릭-> 테이블 데이터 가져 오기 ...

DbVisualizer import GUI


Most other solutions here require that you create the table in advance/manually. This may not be practical in some cases (e.g., if you have a lot of columns in the destination table). So, the approach below may come handy.

Providing the path and column count of your csv file, you can use the following function to load your table to a temp table that will be named as target_table:

The top row is assumed to have the column names.

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;

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

  1. create a table first

  2. Then use copy command to copy the table details:

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

Thanks


Personal experience with PostgreSQL, still waiting for a faster way.

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.

Right click the table name choose import.

enter image description here

If you still have problem, please refer this tutorial. http://www.postgresqltutorial.com/import-csv-file-into-posgresql-table/


Use this SQL code

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

the header keyword lets the DBMS know that the csv file have a header with attributes

for more visit http://www.postgresqltutorial.com/import-csv-file-into-posgresql-table/


IMHO, the most convenient way is to follow "Import CSV data into postgresql, the comfortable way ;-)", using csvsql from csvkit, which is a python package installable via pip.


In Python, you can use this code for automatic PostgreSQL table creation with column names:

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)

It's also relatively fast, I can import more than 3.3 million rows in about 4 minutes.


Create table and have required columns that are used for creating table in csv file.

  1. Open postgres and right click on target table which you want to load & select import and Update the following steps in file options section

  2. Now browse your file in filename

  3. Select csv in format

  4. Encoding as ISO_8859_5

Now goto Misc. options and check header and click on import.


If you need simple mechanism to import from text/parse multiline CSV you could use:

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


I created a small tool that imports csv file into PostgreSQL super easy, just a command and it will create and populate the tables, unfortunately, at the moment all fields automatically created uses the type TEXT

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

The tool can be found on https://github.com/eduardonunesp/csv2pg


How to import CSV file data into a PostgreSQL table?

steps:

  1. Need to connect postgresql database in terminal

    psql -U postgres -h localhost
    
  2. Need to create database

    create database mydb;
    
  3. Need to create user

    create user siva with password 'mypass';
    
  4. Connect with database

    \c mydb;
    
  5. Need to create schema

    create schema trip;
    
  6. Need to create table

    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. Import csv file data to 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. Find the given table data

    select * from trip.test;
    

참고URL : https://stackoverflow.com/questions/2987433/how-to-import-csv-file-data-into-a-postgresql-table

반응형