容我開頭啰嗦一下。一直以來,我和 MySQL 這位久經考驗的老朋友合作愉快。但自從了解了一點 PostgreSQL 后, 對其豐富的功能特性就十分著迷。比如字段類型原生支持 json, xml 和 array。跟 MySQL 比起來,感覺 PostgreSQL 更高級一些。
安裝brew
官方文檔:
http://mxcl.github.com/homebrew/
先安裝Git,打開一個shell:
1
2
3
4
5
6
7
|
cd /usr/local sudo mkdir homebrew curl -L https: //github .com /mxcl/homebrew/tarball/master | sudo tar xz --strip 1 -C homebrew cd homebrew /bin . /brew - v file brew cat brew | moresudo . /brew update |
如果“brew update”命令執行出錯,請確保文件夾/usr/local的所有者權限是你本人而不是root:
1
|
sudo chown $USER /usr/localbrew updat |
在".bash_profile"中更新路徑配置
(如果~下沒有文件".bash_profile" 請執行: touch '.bash_profile' )
1
|
vim '.bash_profile' |
加入
1
|
export PATH=$PATH:/usr/local/homebrew/bin |
之后可以直接執行brew(不用./brew)
如果有了Git可以這樣安裝(未測試)
1
2
3
4
|
git clone https: //github .com /mxcl/homebrew .git cd homebrew /bin cd homebrew /bin . /brew - v |
安裝測試
1
2
3
|
. /brew install wget . /brew uninstall wget . /brew searc /apache */ |
安裝PostgreSQL
使用 brew 一句搞定。
1
|
brew install postgres |
初始化數據庫
1
|
initdb /usr/local/var/postgres |
啟動或停止數據庫
啟動服務:
1
|
pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server .log start |
停止服務:
1
|
pg_ctl -D /usr/local/var/postgres stop -s -m fast |
如果先嫌麻煩,可以加入開機自動啟動
1
|
ln -sfv /usr/local/opt/postgresql/ *.plist ~ /Library/LaunchAgents |
常用操作
1.創建一個 PostgreSQL 用戶
1
2
3
|
createuser username -P #Enter password for new role: #Enter it again: |
上面的 username 是用戶名,回車輸入 2 次用戶密碼后即用戶創建完成。更多用戶創建信息可以 "createuser --help" 查看。
2.創建數據庫
1
|
createdb dbname -O username -E UTF8 -e |
上面創建了一個名為 dbname 的數據庫,并指定 username 為改數據庫的擁有者(owner),數據庫的編碼(encoding)是 UTF8,參數 "-e" 是指把數據庫執行操作的命令顯示出來。
更多數據庫創建信息可以 "createdb --help" 查看。
3.連接數據庫
1
|
psql -U username -d dbname -h 127.0.0.1 |
心得體會
還在學習中,大致覺得跟 MySQL 區別不大,都是執行標準的 SQL 語句。目前就發現 limit 語句跟 MySQL 有區別。比如 MySQL 中取前 10 條記錄:
1
|
select * from table limit 0, 10 |
而在 PostgreSQL 中則是:
1
|
select * from table limit 10 offset 0 |
這樣一看,倒覺得 PostgreSQL 的看起來更清晰一些。MySQL 中的 offset 是可選項,熟悉了以后用起來無妨,剛開始學時就很容易會分不清 offset 和 limit 值的位置。