本文Centos版本為7.4,安裝的Postgresql版本為9.4。
1.查找需要安裝的版本:
可以下載9.3以下的版本:https://yum.postgresql.org/repopackages.php
查看9.4以上的版本:https://download.postgresql.org/pub/repos/yum/
2.使用root用戶登錄,安裝yum源:
yum install https://download.postgresql.org/pub/repos/yum/9.4/redhat/rhel-7-x86_64/pgdg-centos94-9.4-3.noarch.rpm
下載路徑為:
[root@localhost yum-root-v9tlUe]# pwd /var/tmp/yum-root-v9tlUe
[root@localhost yum-root-v9tlUe]# ls pgdg-centos94-9.4-3.noarch.rpm
3.安裝Postgresql
yum install -y postgresql94-server postgresql94-contrib
初始化數據庫:
查看數據庫有沒有初始化
ll -lhtr /var/lib/pgsql/9.4/data/
如果初始化過,把之前的數據庫刪除掉,在初始化。
rm -rf /var/lib/pgsql/9.4/data/* /var/lib/pgsql /usr/pgsql-9.4
初始化:
/usr/pgsql-9.4/bin/postgresql94-setup initdb
4.修改Postgresql用戶密碼(安裝完之后,會自動生成一個postgres用戶)
切換postgres用戶:
su - postgres
登錄數據庫:
psql -U postgres
可能會出現以下錯誤:(重啟psql再進入,systemctl restart postgresql-9.4.service)
更新密碼:
ALTER USER postgres with encrypted password 'abc123';
5.配置遠程訪問:
vi /var/lib/pgsql/9.4/data/postgresql.conf
找到listen_addresses = 'localhost' ,將 localhost 改為 *
vi /var/lib/pgsql/9.4/data/pg_hba.conf
如果允許本地項目訪問,將local、IPv4、IPv6的peer改為trust
並在IPv4增加一行:
host all all 0.0.0.0/0 md5
重啟服務:
systemctl restart postgresql-9.4.service
防火牆設置:
firewall-cmd --add-service=postgresql --permanent
firewall-cmd --reload
可以用其他工具連接。
6.相關命令
systemctl restart postgresql-9.4.service #重啟服務 systemctl enable postgresql-9.4.service #設置開機自啟 systemctl start postgresql-9.4.service #開啟服務 systemctl status postgresql-9.4.service #查看服務狀態
數據庫相關操作:
\q #退出postgresql
\l #查看所有數據庫
\dt #查看數據庫表
\d test #查看表結構
\c dbname #切換數據庫
\i /pathA/xxx.sql #執行某個sql文件