將 CSV 檔案資料匯入 PostgreSQL 中的表

將 CSV 檔案資料匯入 PostgreSQL 中的表

CSV 檔案是具有 .csv 副檔名且內容以逗號分隔的文字檔案。該檔案可以實現不同的目標,例如將資料載入到資料庫表中以及將資料匯入到 Google 和 Excel 電子表格中。

在使用電子表格時,你還可以將資料匯出到 CSV 檔案並在其他功能中使用這些資料。

本教程將演示如何使用 CSV 檔案在 PostgreSQL 資料庫中填充表。

將 CSV 檔案資料匯入 PostgreSQL 表的分步指南

  1. 使用以下命令登入 PostgreSQL 伺服器。在提示中輸入你的密碼並按下回車鍵。

    david@david-HP-ProBook-6470b:~$ psql -U postgres
    Password for user postgres:
    
  2. 建立一個資料庫,我們將在其中放置 CSV 檔案中的資料。

    postgres=# create database csv_db;
    
  3. 連線到資料庫 csv_db

    postgres=# \c csv_db;
    You are now connected to database "csv_db" as user "postgres".
    
  4. 建立一個名為 product 的表,其中包含 idproduct_nameproduct_typeproduct_price 列。

```psql
csv_db=# CREATE table product(
csv_db(# id SERIAL UNIQUE NOT NULL,
csv_db(# product_name varchar(50),
csv_db(# product_type varchar(50),
csv_db(# product_price integer,
csv_db(# PRIMARY KEY(id));
CREATE TABLE
```
  1. 建立一個 CSV 檔案並建立產品表的一些例項。你可以將檔案命名為 data.csv 或你喜歡的任何名稱。

    Iphone 7,    500,  phone
    HP probook,  8000, computer
    Canon pixma, 3000,  printer
    
  2. 要將資料從 CSV 檔案複製到產品表,請使用 copy 命令,並附帶 CSV 檔案的絕對路徑和分隔列的分隔符。由於 id 是自動生成的,我們可以指定 product_nameproduct_priceproduct_type 作為我們想要插入資料庫的唯一欄位。

    csv_db=# \copy product(product_name, product_price, product_type) FROM '/home/david/Documents/work/upwork/jhinku-tutorials/data.csv' DELIMITER ',' CSV;
    COPY 3
    
  3. 執行以下查詢,確認我們已經成功將資料插入到產品表中。

    csv_db=# select * from product;
    
輸出:

```text
 id | product_name | product_type | product_price
----+--------------+--------------+---------------
  1 | Iphone 7     |   phone      |           500
  2 | HP probook   |  computer    |          8000
  3 | Canon pixma  |   printer    |          3000
(3 rows)
```
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
David Mbochi Njonge avatar David Mbochi Njonge avatar

David is a back end developer with a major in computer science. He loves to solve problems using technology, learning new things, and making new friends. David is currently a technical writer who enjoys making hard concepts easier for other developers to understand and his work has been published on multiple sites.

LinkedIn GitHub

相關文章 - Postgres Table