使用Homebrew来操作PostgreSQL的Mac

由于反复查询同样的事情,所以我整理了一下。

列出可安装的版本

带有✔标志的项目已经安装完成。

$ brew search postgresql
==> Formulae
postgresql@10 ✔️   postgresql@13     postgresql@9.4    postgrest
postgresql@11     postgresql@14     postgresql@9.5
postgresql@12     postgresql@15     qt-postgresql

进行安装

推荐使用指定版本进行安装,如 @11。

$ brew install postgresql@11

卸载

$ brew uninstall postgresql@11

版本确认

$ psql --version
psql (PostgreSQL) 11.5

符号链接

如果没有创建符号链接,则版本可能无法正确切换。建议使用 link / unlink 来切换所需的版本。

用法

$ brew unlink postgresql@10
$ brew link postgresql@11

启动 PostgreSQL

$ brew services start postgresql@11
==> Successfully started `postgresql` (label: homebrew.mxcl.postgresql)

检查启动状态

如果有多个版本同时运行,通常绿色的“已启动”会变成黄色。只需启动一个版本,其他版本应停止运行。

$ brew services list
Name           Status  User  Plist
mysql          stopped       
postgresql@11  started yuppy /Users/yuppy/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
postgresql@10  stopped       

停用PostgreSQL

$ brew services stop postgresql@11
Stopping `postgresql`... (might take a while)
==> Successfully stopped `postgresql` (label: homebrew.mxcl.postgresql)

展示DB列表

会显示正在使用的数据库列表。

$ psql -l
               Name                | Owner | Encoding | Collate | Ctype | Access privileges 
-----------------------------------+-------+----------+---------+-------+-------------------
 postgres                          | yuppy | UTF8     | C       | C     |  
 template0                         | yuppy | UTF8     | C       | C     | =c/yuppy         +
                                   |       |          |         |       | yuppy=CTc/yuppy
 template1                         | yuppy | UTF8     | C       | C     | =c/yuppy         +
                                   |       |          |         |       | yuppy=CTc/yuppy
(3 rows)

数据库操作

由于经常进行深入研究,顺便记下来。

进入数据库

$ psql 入りたいデータベース名

显示表格列表

同时按下 Option 键和 ¥ 键。

# \dt

数据库切换

# \c 切り替えたいデータベース名

删除数据库

# drop database 削除したいデータベース名

从数据库中出来

# \q

附上补充说明

当更改版本后,出现了错误状态并且无法工作,因此我创建了以下文章。

 

bannerAds