PostgreSQL 数据库安装使用

12.18'23

介绍

PostgreSQL 是流行的开源对象关系型数据库。

参考:How To Install and Use PostgreSQL on Ubuntu 18.04 | DigitalOcean

安装

Ubuntu

sudo apt update
sudo apt install postgresql

服务默认开机会自动启动

systemctl status postgresql
systemctl stop postgresql
systemctl start postgresql

systemctl disable postgresql
systemctl enable postgresql

使用管理员账号 postgres 执行命令 psql, ,默认端口5432

sudo -u postgres psql

会进入命令行客户端

postgres=# 

默认无密码,修改密码

postgres=# \password postgres
Enter new password:
...

MacOS

brew install postgresql@16
brew services start postgresql@16

echo 'export PATH="/opt/homebrew/opt/postgresql@16/bin:$PATH"' >> ~/.zshrc
createdb
psql

user=#

默认用户为当前登录用户

创建用户和数据库

create user postgres;
create database ...;

授权用户

ALTER USER postgres CREATEDB;

postgres 登录

psql -U postgres

服务

服务默认开机会自动启动

systemctl status postgresql
systemctl stop postgresql
systemctl start postgresql

systemctl disable postgresql
systemctl enable postgresql

表管理

postgres=#可以运行特殊命令,一般以\开头。

CommandMeaning
\hHelp
\dList of relations(tables)
\lList of databases
\c Connect to database
\qQuit

postgres=#里面可以直接运行 SQL 语句,以;结尾。

CREATE TABLE table_name (
    column_name1 col_type (field_length) column_constraints,
    column_name2 col_type (field_length),
    column_name3 col_type (field_length)
);

新建用户和数据库

psql

创建数据库

create database name

创建用户(role)

create user name

设置用户密码

sudo -Hiu postgres psql

postgres=# \password <username>
Enter new password:
Enter it again:
postgres=# \q

密码校验错误

可能需要修改 pg_hba.conf,修改 peermd5

locate pg_hba.conf

Data Types

https://www.postgresql.org/docs/current/datatype.html

:DBUI postgresql:[database] postgresql://[user[:password]@][host][:port]/[database]

see https://github.com/tpope/vim-dadbod/blob/master/doc/dadbod.txt

Example

postgresql:database postgresql://user:password@localhost/database

编程语言支持

go

📖