将 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