Postgres操作

docker 启动 postgres

1
docker run --name postgres-test -e POSTGRES_PASSWORD=123456 -p 5432:5432 -d postgres

登录到启动的 postgres 容器中

1
docker exec -it <container> /bin/bash

登录 Postgres 数据库

1
2
3
4
# 切换到 postgres 用户
# su - postgres
# 执行 postgres 的客户端
$ psql

查看表名

1
postgres=# \d [tablename]

命令行执行 SQL

1
psql [dbname] -U <username> -c "SQL语句"
1
psql [dbname] -U <username> -f sql文件

例如:查询uts库下所有表

1
psql -U uts -c "select tablename from pg_tables where schema='public'"

例如:在命令行执行SQL文件

1
psql -U uts -f /root/devops/uts-pg/uts_sql.sql

导出数据

通过 copy 方式指定表导出

1
copy (select * from storage_threat_ips_24 ) to '/opt/nsfocus/data/hadoop/vdb/utsgpback/storage_threat_ips_24.csv' with csv header;

注意,该方式仅会导出数据,没有表结构。

导出表结构

1
pg_dump [-h host -p port] -U <username> -s -t <tablename> > 导出文件.sql

-s : 只导出表结构,不会导出数据;

-t : 指定要导出的数据库表;

本地导出不用添加主机和端口。

  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2022-2023 ligongzhao
  • 访问人数: | 浏览次数:

请我喝杯咖啡吧~

支付宝
微信