当前位置:网站首页>PostgreSQL — Installation and Common Commands

PostgreSQL — Installation and Common Commands

2022-08-10 20:56:00 wind and clouds

Docker安装

安装命令

$ docker run --name postgres -e POSTGRES_PASSWORD=[email protected] -p 5432:5432 -d postgres:14.2 

环境变量

  • POSTGRES_PASSWORD:必填.Set a password for the default superuser.
  • POSTGRES_USER:Create a user with superuser privileges,Also create a database with the same name.常与POSTGRES_PASSWORD组合使用.
  • POSTGRES_DB:A default database is created when the container starts.没有指定则使用POSTGRES_USER的值.
  • PGDATA:Specifies the location of the database file.默认/var/lib/postgresql/data

常用命令

登录数据库

$ psql -U ${user_nam} -d ${db_name} -h ${server_ip} -p 5432

控制台命令

  • \h:查看SQL命令的解释,比如\h select.
  • ?:查看psql命令列表.
  • \l:列出所有数据库.
  • \c [database_name]:连接其他数据库.
  • \d:列出当前数据库的所有表格.
  • \d [table_name]:列出某一张表格的结构.
  • \du:列出所有用户.
  • \e:打开文本编辑器.
  • \conninfo:列出当前数据库和连接的信息.

创建用户及数据库

  # 创建用户及密码
$ create user ${user_name} with password ${user_password};
  # Create a database and specify a user
$ create database ${db_name} owner ${user_name};
  # Grants the user all privileges on the specified database
$ grant all on database ${db_name} to ${user_name};

数据库操作

# 创建新表 
CREATE TABLE t_user(name VARCHAR(20), password VARCHAR(20));
# 插入数据 
INSERT INTO t_user(name, password) VALUES('kevin', '[email protected]');
# 选择记录 
SELECT * FROM t_user;
# 更新数据 
UPDATE t_user set name = 'jack' WHERE name = 'kevin';
# 删除记录 
DELETE FROM t_user WHERE name = 'jack' ;
# 添加新列 
ALTER TABLE t_user ADD email VARCHAR(40);
# 更改表结构 
ALTER TABLE t_user ALTER COLUMN password SET NOT NULL;
# 更改列名
ALTER TABLE t_user RENAME COLUMN name TO username;
# 删除列 
ALTER TABLE t_user DROP COLUMN email;
# 更改表名
ALTER TABLE t_user RENAME TO t_user_info;
# 删除表
DROP TABLE IF EXISTS t_user_info;
原网站

版权声明
本文为[wind and clouds]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/222/202208102027335431.html