PostgreSQL — installation and common commands

Docker installation

install command

$ docker run --name postgres -e POSTGRES_PASSWORD=P@ssw0rD -p 5432:5432 -d postgres:14.2 

environment variable

  • POSTGRES_PASSWORD : Required. Set a password for the default superuser.
  • POSTGRES_USER : Create a user with superuser privileges and create a database with the same name. Often POSTGRES_PASSWORDused in combination with .
  • POSTGRES_DB : A default database is created when the container starts. POSTGRES_USERValue used if not specified .
  • PGDATA : Specifies the location of the database file. default/var/lib/postgresql/data

Common commands

login database

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

console command

  • \h: View the explanation of SQL commands, such as \h select.
  • ?: View the list of psql commands.
  • \l: List all databases.
  • \c [database_name]: connect to other databases.
  • \d: List all tables in the current database.
  • \d [table_name]: List the structure of a table.
  • \du: List all users.
  • \e: Open a text editor.
  • \conninfo: List current database and connection information.

Create users and databases

  # 创建用户及密码
$ create user ${user_name} with password ${user_password};
  # 创建数据库并指定用户
$ create database ${db_name} owner ${user_name};
  # 授予用户在指定数据库的所有权限
$ grant all on database ${db_name} to ${user_name};

database operation

# 创建新表 
CREATE TABLE t_user(name VARCHAR(20), password VARCHAR(20));
# 插入数据 
INSERT INTO t_user(name, password) VALUES('kevin', 'P@ssw0rD');
# 选择记录 
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;

Guess you like

Origin blog.csdn.net/weixin_45804031/article/details/126235853