建议用Homebrew安装postgreSQL

先安装Homebrew ,但是Homebrew依赖于Xcode Command Line Tools,所以需先打开终端执行:

xcode-select --install

在终端中执行安装Homebrew:

/usr/bin/ruby-e"$(curl-fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

检查是否已安装成功:

$ brew -v
Homebrew 1.6.1
Homebrew/homebrew-core (git revision 0aeb7; last commit 2018-04-12)
homebrew安装postgreSQL:
brew install postgresql

安装完postgresql之后需要初始化数据库:

initdb /usr/local/var/postgres -E utf8

如果你不初始化,那么db的路径就是上面的/usr/local/var/postgres(在MacOS 10.11上),数据库编码类型就是utf8.

设置开机启动postgresql服务:

ln -sfv /usr/local/opt/postgresql/*.plist ~/Library/LaunchAgents
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

第一句将postgresql的配置plist文件做软连接至系统的对应路径下,第二句加载其中的一个plist文件。有可能你的postgresql不是通过homebrew安装的,你的plist文件名会略有不同,你只需要自行到/usr/local/opt/postgresql/中找到正确的文件名就可以了。

下面是启动和停止postgresql服务的指令:

pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start
pg_ctl -D /usr/local/var/postgres stop -s -m fast

这里有一点就是往往我们用上面的停止命令会等待一会,然后提示无法停止服务:

pg_ctl -D /usr/local/var/postgres stop -s -m fast
pg_ctl: server does not shut down

这时你可以先卸载掉之前自动加载的服务,然后再尝试停止即可:

launchctl unload -w ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

启动后,我们可以尝试添加username这个用户:

createuser username -P
#Enter password for new role:
#Enter it again:

然后我们可以用刚创建的用户建立一个数据库:

createdb database_Liwen -O username -E UTF8 -e

上面创建了一个名为database_Liwen的数据库,数据库的所有者为username用户,数据库的编码utf-8,-e表示把数据库执行操作的命令显示出来。更多命令可以通过createdb –help查看。

在MacOS中管理postgresql的数据库有2种方法,一种是console,另一种是通过gui(图形化):

console方式,用psql之类来连接数据库:

psql -U username -d database_Liwen  -h 168.130.32.1

进入之后你可以用\h显示SQL的各种命令,用\?来显示psql客户端自身的一些命令,比如\d是显示数据库中的表,\c database_name是连接到指定数据库等等。

如果你不连接postgresql的情况下,也可以看到已创建数据库的列表:

psql -l

gui方式,安装图形化管理软件:

https://www.pgadmin.org

pg数据库 给schema赋建表权限 pg数据库添加用户_postgresql 安装