以前抽資料都是從其他資料庫抽取到postgres資料庫的是以選擇kettle。新項目需求裡需要把客戶給的csv檔案資料抽到postgresql,其中還需要對相關字段進行清洗。先聲明下kettle也可以實作,但是總感覺依賴第三方軟體抽資料不如直接操作資料庫,除非逼不得已,盡量不用(純屬個人見解)。于是就研究linux直接連接配接資料庫處理這部分需求。代碼如下
#!/bin/bash
# *****************************************************
# ** linux_schedule_test
# *****************************************************
#\copy test from '/etl-script/test.csv' delimiter ',' csv header encoding 'UTF8';
# copy test_copy to 'D:\test_copy1.csv' delimiter ',' csv header encoding 'GBK';
export PATH=/usr/pgsql-10/bin:/usr/bin;
psql "host=127.0.0.1 port=5434 user=admin password=123456 dbname=linux_schedule_test" << EOF #2>/dev/null
\copy test from '/etl-script/test.csv' delimiter ',' csv header encoding 'GBK';
create table test$(date +%Y%m%d_%H%m%S) as select * from test;
\q
EOF
export PATH=/usr/pgsql-10/bin:/usr/bin :因為環境作用域問題,最好在腳本開始處将要用到的指令添加PATH路徑。
psql "host=127.0.0.1 port=5434 user=admin password=123456 dbname=linux_schedule_test" :連接配接資料庫
<< EOF : 通過重定向,停留在psql用戶端。
#2>/dev/null 腳本出錯不輸出,調試時建議注釋掉,不然都不知道腳本為什麼沒有跑。
\copy test from '/etl-script/test.csv' delimiter ',' csv header encoding 'GBK';:通過copy指令抽取csv檔案資料。
create table test$(date +%Y%m%d_%H%m%S) as select * from test;:備份test表資料,測試用的。