gpt4 book ai didi

postgresql - 使用 Postgres 在 docker 中上传 csv 文件

转载 作者:行者123 更新时间:2023-11-29 12:16:53 24 4
gpt4 key购买 nike

我有一个非常规的问题。我在 Postgres 中建立了一个数据库

psql -h 192.168.99.100 -p 15432 -U postgres

并使用以下方法在数据库中创建了一个表:

$ docker=# CREATE TABLE cities (
docker(# name varchar(80),
docker(# location point
docker(# );

但是,我无法将 csv 文件上传到我创建的表格中。你能告诉我怎么做吗?(我正在使用 Docker 命令窗口来执行此操作)提前致谢。

最佳答案

下面是使用容器内的 psql 将 CSV 中的纬度/经度点复制到城市表的示例。

# Sample CSV data
echo "somecity",45,-45 > cities.csv

# Create database
docker run --name postgres -p 15432:5432 -d postgres

# Create cities table and a temp table for loading point coordinates
# Uses host network to access database published on port 15432 of the host
docker run --rm --network=host postgres psql -h localhost -p 15432 -U postgres -c '
CREATE TABLE temp (
name varchar(80),
latitude numeric(12,8),
longitude numeric(12,8)
);
CREATE TABLE cities (
name varchar(80),
location point
);'

# \copy data from file (mounted by volume)
docker run --rm --network=host -v `pwd`:/data postgres \
psql -h localhost -p 15432 -U postgres -c \
"\\copy temp FROM '/data/cities.csv' WITH csv"

# Insert into cities creating point from coordinates
docker run --rm --network=host postgres psql -h localhost -p 15432 -U postgres -c "
INSERT INTO cities (name, location)
SELECT name, point(temp.latitude,temp.longitude)
FROM temp;
DROP TABLE temp"

# Show the point
docker run --rm --network=host postgres psql -h localhost -p 15432 -U postgres -c \
"SELECT * FROM cities;"

最后一条命令输出:

  name   | location
----------+----------
somecity | (45,-45)
(1 row)

关于postgresql - 使用 Postgres 在 docker 中上传 csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48670755/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com