PostgreSQL常用操作
docker启动
docker run --name postgres -d -p 5432:5432 -e POSTGRES_PASSWORD=123456 -e POSTGRES_USER=admin -e POSTGRES_DB=myapp postgres
数据库常用操作
#连接数据库
psql -h localhost -U admin -W -d myapp
#查看数据库列表
\l
#创建数据库
create database myapp
#选择数据库
\c myapp
#查看数据表列表
\d
#创建数据表
create table company(
id int primary key not null,
name text not null
);
#插入数据
insert into company(id,name) values(1,'test');
#查询数据
select * from company;
#更新数据
update company set name='newtest' where id=1;
#删除数据
delete from company;
#创建用户
createuser postgres -P -U admin -W
#修改密码
alter role postgres with password 'postgres';
#增加用户权限
alter role postgres superuser createrole createdb;
#查看所有用户及权限相关信息
\du
注:在使用过程中发,分号非常重要不能省略。
数据导出
# -s 选项用来只导出表结构,而不会导出表中的数据
# -t 选项用来指定要导出的数据库表
docker exec -it postgres pg_dump -U admin -s -d myapp -t company > ./company.sql
数据导入
docker exec -i postgres psql -U admin myapp < ./company.sql
建库、用户及授权
psql -U postgres -W
create user "TestUser" with password 'test';
create database "TestDb" owner "TestUser";
grant all privileges on database "TestDb" to "TestUser";
注:postgres默认是大小写不敏感的,如果需要用大写,引号不可省略,切记分号也不可以省略。