1.命令格式

Usage:
  psql [OPTION]... [DBNAME [USERNAME]]

常用示例:

psql -f /insert_simple.sql   (不指定用户名则默认是postgres)

psql -d test -f /insert_simple.sql (指定数据库为test)

2.示例——postgres用户下执行用户数据库初始化

*docker容器形式的PostgreSQL数据库环境

学习的命令示例:psql -f /insert_simple.sql   (不指定用户名则默认是postgres)

文件名:insert_simple.sql

文件内容如下:

create database test;
\c test;
create table simple(
id int primary key,
name varchar(50),
description varchar(100));
insert into simple(id,name,description)values(1,'name1','aaa');
insert into simple(id,name,description)values(2,'name22','aaa2')on conflict(id) do update set name=excluded.name,description=excluded.description;
insert into simple(id,name,description)values(3,'name3','aaa')on conflict do nothing;

step1:docker宿主linux操作系统上执行:

docker ps|grep postgres

docker cp insert_simple.sql ee2987ffcbc9:/

docker exec -it ee2987ffcbc9 /bin/sh

step2:从前面第一步后,进入了docker容器,继续执行

# su - postgres
postgres@ee2987ffcbc9:~$ psql -f /insert_simple.sql
psql:/insert_simple.sql:1: ERROR:  database "test" already exists
You are now connected to database "test" as user "postgres".
CREATE TABLE
INSERT 0 1
INSERT 0 1
INSERT 0 1
postgres@ee2987ffcbc9:~$ psql
psql (10.17 (Debian 10.17-1.pgdg90+1))
Type "help" for help.

postgres=# \c test
You are now connected to database "test" as user "postgres".
test=# select * from simple;
 id |  name  | description
----+--------+-------------
  1 | name1  | aaa
  2 | name22 | aaa2
  3 | name3  | aaa
(3 rows)

test=# \q
postgres@ee2987ffcbc9:~$ exit
logout
# exit

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐