[转] Mac 下 PostgreSQL 的安装与使用

在 mac 下,可以利用 homebrew 直接安装 PostgreSQL:

1
brew install postgresql -v

稍等片刻,PostgreSQL 就安装完成。接下来就是初始数据库,在终端执行一下命令,初始配置 PostgreSQL:

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

上面指定 "/usr/local/var/postgres" 为 PostgreSQL 的配置数据存放目录,并且设置数据库数据编码是 utf8,更多配置信息可以 "initdb --help" 查看。

设成开机启动 PostgreSQL:

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

启动 PostgreSQL:

1
pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start

关闭 PostgreSQL:

1
pg_ctl -D /usr/local/var/postgres stop -s -m fast

创建一个 PostgreSQL 用户

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

上面的 username 是用户名,回车输入 2 次用户密码后即用户创建完成。更多用户创建信息可以 "createuser --help" 查看。

创建数据库

1
createdb dbname -O username -E UTF8 -e

上面创建了一个名为 dbname 的数据库,并指定 username 为改数据库的拥有者(owner),数据库的编码(encoding)是 UTF8,参数 "-e" 是指把数据库执行操作的命令显示出来。

更多数据库创建信息可以 "createdb --help" 查看。

连接数据库

1
psql -U username -d dbname -h 127.0.0.1

WARNING: enabling "trust" authentication for local connections

You can change this by editing pg_hba.conf or using the option -A, or

--auth-local and --auth-host, the next time you run initdb.

Success. You can now start the database server using:

/usr/local/Cellar/postgresql/9.5.1/bin/pg_ctl -D /usr/local/var/postgres -l logfile start

==> Caveats

If builds of PostgreSQL 9 are failing and you have version 8.x installed,

you may need to remove the previous version first. See:

https://github.com/Homebrew/homebrew/issues/2510

To migrate existing data from a previous major version (pre-9.0) of PostgreSQL, see:

http://www.postgresql.org/docs/9.5/static/upgrading.html

To migrate existing data from a previous minor version (9.0-9.4) of PosgresSQL, see:

http://www.postgresql.org/docs/9.5/static/pgupgrade.html

You will need your previous PostgreSQL installation from brew to perform `pg_upgrade`.

Do not run `brew cleanup postgresql` until you have performed the migration.

To have launchd start postgresql at login:

ln -sfv /usr/local/opt/postgresql/*.plist ~/Library/LaunchAgents

Then to load postgresql now:

launchctl load ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist

Or, if you don't want/need launchctl, you can just run:

postgres -D /usr/local/var/postgres

==> Summary

上一篇:mac 下用 brew 安装mongodb


下一篇:Cordova插件开发