Linux连接数据库
本机连接
1root@VM-12-5-debian:~# su - postgres # 切换用户环境2postgres@VM-12-5-debian:~$ psql # 连接数据库,默认用户和数据库都是postgres3psql (15.7 (Debian 15.7-0+deb12u1))4Type "help" for help.5
6postgres=#
连接其他数据库
1# psql -h 服务器地址 -p 数据库端口号 -U 用户名2cirry@VM-12-5-debian:~$ psql -h xxxx.xxxx.xxx -p 5432 -U postgres3Password for user postgres:4psql (15.7 (Debian 15.7-0+deb12u1))5SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, compression: off)6Type "help" for help.7
8postgres=#
退出连接
1postgres=# \q2# 或者 直接输入 ctrl + d
库操作
1# 查询数据库2postgres=# \l3 List of databases4 Name | Owner | Encoding | Collate | Ctype | ICU Locale | Locale Provider | Access privileges5------------+----------+----------+------------+------------+------------+-----------------+-----------------------6 astro-blog | postgres | UTF8 | en_US.utf8 | en_US.utf8 | | libc |7 mydb | postgres | UTF8 | en_US.utf8 | en_US.utf8 | | libc |8
9# 创建数据库10# create database 数据库名;11postgres=# create database mydb;12CREATE DATABASE13
14# 切换数据库15# \c 数据库名;7 collapsed lines
16postgres=# \c mydb;17You are now connected to database "mydb" as user "postgres".18
19# 删除数据库20# drop database 数据库名;21postgres=# drop database mydb;22DROP DATABASE
表操作
Postgres中三类主要数据类型:
- 数值数据类型
- 字符串数据类型
- 时间/日期数据类型
数值类型:
名称 | 存储长度 | 描述 | 范围 |
---|---|---|---|
smallint | 2字节 | 小范围整数 | -32768 ~ +32768 |
integer | 4字节 | 常用整数 | -2147483648 ~ +2147483647 |
bigint | 8字节 | 大范围整数 | -9223372036854775808 ~ +9223372036854775807 |
decimal | 可变长 | 用户指定的精度,精确 | 小数点前131072位 ~ 小数点后16383位 |
numeric | 可变长 | 用户指定的精度,精确 | 小数点前131072位 ~ 小数点后16383位 |
real | 4字节 | 可变精度,不精确 | 6位十进制数字精度 |
double | 8字节 | 可变精度,不精确 | 15位十进制数字精度 |
字符串类型:
- char(size), character(size): 固定长度字符串,size规定需存储的字符数,由右边的空格补齐;
- varchar(size), character varying(size): 可变长度字符串,size规定需存储的字符数;
- text: 可变长度字符串。
日期/时间类型:
- timestamp: 日期和时间,时间戳;
- date: 日期, 无时间;
- time: 时间。
自增标识字段:
伪类型 | 存储长度 | 范围 |
---|---|---|
smallserial | 2字节 | 1 ~ 32768 |
serial | 4字节 | 1 ~ 2147483647 |
bigserial | 8字节 | 1 ~ 9223372036854775807 |
其它的数据类型还有布尔值,货币数额和几何数据等等。
创建表
1mydb=# create table test(id serial primary key, name varchar(255));2CREATE TABLE
查询表和表结构
1# 查询表2mydb-# \d3 List of relations4 Schema | Name | Type | Owner5--------+-------------+----------+----------6 public | test | table | postgres7 public | test_id_seq | sequence | postgres8(2 rows)9
10# 查询指定表结构11mydb=# \d test;12 Table "public.test"13 Column | Type | Collation | Nullable | Default14--------+------------------------+-----------+----------+----------------------------------15 id | integer | | not null | nextval('test_id_seq'::regclass)3 collapsed lines
16 name | character varying(255) | | |17Indexes:18 "test_pkey" PRIMARY KEY, btree (id)
插入数据
1mydb=# insert into test(name) values('jack');2INSERT 0 13mydb=# select * from test;4 id | name5----+------6 1 | jack7(1 row)
更新数据
1mydb=# update test set name='mayun' where id=1;2UPDATE 1
删除数据
1mydb=# delete from test where id = 1;2DELETE 1
schema
1mydb=# create schema myschema;2CREATE SCHEMA3mydb=# create table myschema.test(id serial primary key, name varchar(255));4CREATE TABLE
备份数据库
官方文档:pg_dump
备份的格式有几种:
- *.bak: 压缩二进制格式
- *.sql: 明文格式
- *.tar: 压缩格式
1# 备份,注意在postgres用户的shell中执行,不是在pgsl中执行2root@VM-12-5-debian:~# su - postgres3# pg_dump -f 备份文件路径 数据库名4postgres@VM-12-5-debian:~$ pg_dump -f /tmp/mydb.sql mydb5postgres@VM-12-5-debian:~$ ls /tmp6mydb.sql
恢复数据库
注意,恢复数据库前,需要提前创建好数据库。
另外,执行恢复命令是在postgres用户的shell中,而不是在psql控制台中。
1root@VM-12-5-debian:~# su - postgres # 切换用户2postgres@VM-12-5-debian:~$ psql # 进入psql控制台3postgres=# create database mydb; # 创建数据库4postgres=# \q # 退出psql控制台5# psql -f 恢复文件路径 数据库名6postgres@VM-12-5-debian:~$ psql -f /tmp/mydb.sql mydb # 执行恢复命令
用户操作
增删改查
1postgres=# create user test with password '123456';2CREATE ROLE3# 查询用户4postgres=# \du5 List of roles6 Role name | Attributes | Member of7-----------+------------------------------------------------------------+-----------8 postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {}9 test | | {}10
11postgres=# alter user test with password '123456789';12ALTER ROLE13# 未赋予角色权限14postgres=# drop user test15DROP ROLE14 collapsed lines
16# 删除已赋予角色权限的用户,需要移除账户数据库所有权限17postgres=# drop user test;18ERROR: role "test" cannot be dropped because some objects depend on it19DETAIL: privileges for database mydb202 objects in database mydb21# 删除库权限22postgres=# revoke all privileges on database mydb from test;23REVOKE24# 删除表权限25postgres=# \c mydb;26mydb=# revoke all privileges on all tables in schema public from test;27REVOKE28mydb=# drop user test;29DROP ROLE
使用其他用户登录
1postgres=# \q2postgres@VM-12-5-debian:~$ psql -U test -d mydb3psql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL: Peer authentication failed for user "test"
提示认证失败,需要修改配置文件。
1# vim /etc/postgresql/[数据库版本号]/main/pg_hba.conf2root@VM-12-5-debian:~# vim /etc/postgresql/15/main/pg_hba.conf3# ... 找到下面这一行修改后面的 peer 为 md54# "local" is for Unix domain socket connections only5local all all peer6local all all md57# ...8# 修改完成之后重启postgres9root@VM-12-5-debian:~# systemctl restart postgresql
再使用新创建的用户登录:
1postgres@VM-12-5-debian:~$ psql -U test -d mydb;2Password for user test:3psql (15.7 (Debian 15.7-0+deb12u1))4Type "help" for help.5
6# 查看所有表7mydb=> \d8 List of relations9 Schema | Name | Type | Owner10--------+-------------+----------+----------11 public | test | table | postgres12 public | test_id_seq | sequence | postgres13(2 rows)14
15# 查询表内容,提示无权限3 collapsed lines
16mydb=> select * from test;17ERROR: permission denied for table test18mydb=> \q
用户授权
1# postgres用户授权库权限给test2postgres=# grant all privileges on database mydb to test;3GRANT4# 切换到mydb库中5postgres=# \c mydb;6You are now connected to database "mydb" as user "postgres".7# 将mydb的表权限授权给test用户8mydb=# grant all privileges on all tables in schema public to test;9GRANT10mydb=# \q
新用户权限测试
1postgres@VM-12-5-debian:~$ psql -U test -d mydb;2Password for user test:3psql (15.7 (Debian 15.7-0+deb12u1))4Type "help" for help.5
6# 有查询权限了7mydb=> select * from test;8 id | name9----+-------10 2 | jack11 3 | cirry12(2 rows)
角色管理
postgresql里没有区分用户和角色的概念。
1postgres=# create role vip;2CREATE ROLE3postgres=# create user cirry;4CREATE ROLE5postgres=# \du6 List of roles7 Role name | Attributes | Member of8-----------+------------------------------------------------------------+-----------9 cirry | | {}10 postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {}11 vip | Cannot login | {}
区别:创建的角色是没有登录功能的。
角色属性
属性 | 说明 |
---|---|
login | 只有具有login属性的角色可以登录数据库 |
superuser | 数据库超级用户 |
createdb | 创建数据库权限 |
createrole | 允许其创建或删除其他普通用户角色(超级用户除外) |
replication | 流复制用到的用户属性,一般单独设定 |
password | 在登录时使用指定密码登录 |
inherit | 用户组对组员的继承标志,成员可以继承用户组的权限特性 |
创建用户
创建用户外加赋予角色属性示例:
1# 查看用户列表2postgres=# \du3 List of roles4 Role name | Attributes | Member of5-----------+------------------------------------------------------------+-----------6 cirry | | {}7 postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {}8 vip | Cannot login | {}9
10# 给角色添加登录属性11postgres=# alter role vip login;12ALTER ROLE13
14# 查看用户列表15postgres=# \du16 collapsed lines
16 List of roles17 Role name | Attributes | Member of18-----------+------------------------------------------------------------+-----------19 cirry | | {}20 postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {}21 vip | | {}22
23# 创建一个角色指定登录密码和登录功能24postgres=# create role newuser password '123456' login;25CREATE ROLE26postgres=# \q27
28# 新角色登录测试29postgres@VM-12-5-debian:~$ psql -U newuser -d mydb;30Password for user newuser:31psql (15.7 (Debian 15.7-0+deb12u1))
其他功能
1# 查看用户2postgres=# select * from pg_user;3 usename | usesysid | usecreatedb | usesuper | userepl | usebypassrls | passwd | valuntil | useconfig4----------+----------+-------------+----------+---------+--------------+----------+----------+-----------5 postgres | 10 | t | t | t | t | ******** | |6 cirry | 68737 | f | f | f | f | ******** | |7
8
9# 查看角色10postgres=# select * from pg_roles;11 rolname | rolsuper | rolinherit | rolcreaterole | rolcreatedb | rolcanlogin | rolreplication | rolconnlimit | rolpassword | rolvaliduntil | rolbypassrls | rolconfig | oid12---------------------------+----------+------------+---------------+-------------+-------------+----------------+--------------+-------------+---------------+--------------+-----------+-------13 pg_database_owner | f | t | f | f | f | f | -1 | ******** | | f | | 617114 pg_read_all_data | f | t | f | f | f | f | -1 | ******** | | f | | 618115 pg_write_all_data | f | t | f | f | f | f | -1 | ******** | | f | | 618212 collapsed lines
16 pg_monitor | f | t | f | f | f | f | -1 | ******** | | f | | 337317 pg_read_all_settings | f | t | f | f | f | f | -1 | ******** | | f | | 337418 pg_read_all_stats | f | t | f | f | f | f | -1 | ******** | | f | | 337519 pg_stat_scan_tables | f | t | f | f | f | f | -1 | ******** | | f | | 337720 pg_read_server_files | f | t | f | f | f | f | -1 | ******** | | f | | 456921 pg_write_server_files | f | t | f | f | f | f | -1 | ******** | | f | | 457022 pg_execute_server_program | f | t | f | f | f | f | -1 | ******** | | f | | 457123 pg_signal_backend | f | t | f | f | f | f | -1 | ******** | | f | | 420024 pg_checkpoint | f | t | f | f | f | f | -1 | ******** | | f | | 454425 postgres | t | t | t | t | t | t | -1 | ******** | | t | | 1026 vip | f | t | f | f | f | f | -1 | ******** | | f | | 6873627 cirry | f | t | f | f | t | f | -1 | ******** | | f | | 68737
常用命令
1# 修改当前登录用户密码2postgres=> \password3Enter new password for user "newuser":4Enter it again:5# 退出登录6postgres=> \q7# 查看sql命令8postgres=> \h select9# 列出所有数据库10postgres=> \l11 List of databases12 Name | Owner | Encoding | Collate | Ctype | ICU Locale | Locale Provider | Access privileges13------------+----------+----------+------------+------------+------------+-----------------+-----------------------14 astro-blog | postgres | UTF8 | en_US.utf8 | en_US.utf8 | | libc |15 gitea | postgres | UTF8 | en_US.utf8 | en_US.utf8 | | libc |31 collapsed lines
16 memos | postgres | UTF8 | en_US.utf8 | en_US.utf8 | | libc |17
18# 切换其他数据库19postgres=# \c mydb20You are now connected to database "mydb" as user "postgres".21
22# 列出当前数据库的所有表23mydb=# \d24 List of relations25 Schema | Name | Type | Owner26--------+-------------+----------+----------27 public | test | table | postgres28 public | test_id_seq | sequence | postgres29(2 rows)30
31# 列出某一张表格结构32mydb=# \d test;33 Table "public.test"34 Column | Type | Collation | Nullable | Default35--------+------------------------+-----------+----------+----------------------------------36 id | integer | | not null | nextval('test_id_seq'::regclass)37 name | character varying(255) | | |38Indexes:39 "test_pkey" PRIMARY KEY, btree (id)40
41# 列出所有用户42mydb=# \du43 List of roles44 Role name | Attributes | Member of45-----------+------------------------------------------------------------+-----------46 postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {}