Mac安裝PostgreSQL

Mac安裝PostgreSQL

最近在學習rails,記錄下安裝psql的過程

安裝及初始化

這里使用homebrew安裝

brew install postgresql

等待安裝完成后,初始化:

initdb /usr/local/var/postgres

啟動服務:

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

設置開機啟動

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

創(chuàng)建數(shù)據(jù)庫和賬戶

mac安裝postgresql后不會創(chuàng)建用戶名數(shù)據(jù)庫,執(zhí)行命令:

createdb

然后登錄PostgreSQL控制臺:

psql

使用\l命令列出所有的數(shù)據(jù)庫,看到已存在用戶同名數(shù)據(jù)庫、postgres數(shù)據(jù)庫,但是postgres數(shù)據(jù)庫的所有者是當前用戶,沒有postgres用戶。按:q退出查看

之后需要做以下幾件事:

  1. 創(chuàng)建postgres用戶

     CREATE USER postgres WITH PASSWORD 'password';
    
  2. 刪除默認生成的postgres數(shù)據(jù)庫

     DROP DATABASE postgres;
    
  3. 創(chuàng)建屬于postgres用戶的postgres數(shù)據(jù)庫

     CREATE DATABASE postgres OWNER postgres;
    
  4. 將數(shù)據(jù)庫所有權限賦予postgres用戶

     GRANT ALL PRIVILEGES ON DATABASE postgres to postgres;
    
  5. 給postgres用戶添加創(chuàng)建數(shù)據(jù)庫的屬性

     ALTER ROLE postgres CREATEDB;
    

這樣就可以使用postgres作為數(shù)據(jù)庫的登錄用戶了,并可以使用該用戶管理數(shù)據(jù)庫

登錄控制臺指令

psql -U [user] -d [database] -h [host] -p [post]

-U指定用戶,-d指定數(shù)據(jù)庫,-h指定服務器,-p指定端口

上方直接使用psql登錄控制臺,實際上使用的是缺省數(shù)據(jù)

user:當前mac用戶
database:用戶同名數(shù)據(jù)庫
主機:localhost
端口號:5432,postgresql的默認端口是5432

完整的登錄命令,比如使用postgres用戶登錄

psql -U postgres -d postgres

常用控制臺命令

\password:設置當前登錄用戶的密碼
\h:查看SQL命令的解釋,比如\h select。
\?:查看psql命令列表。
\l:列出所有數(shù)據(jù)庫。
\c [database_name]:連接其他數(shù)據(jù)庫。
\d:列出當前數(shù)據(jù)庫的所有表格。
\d [table_name]:列出某一張表格的結構。
\du:列出所有用戶。
\e:打開文本編輯器。
\conninfo:列出當前數(shù)據(jù)庫和連接的信息。
\password [user]: 修改用戶密碼
\q:退出
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容