CentOS7使用yum安装PostgreSQL和PostGIS的方法

  • Post category:Linux

以下是详细讲解“CentOS7使用yum安装PostgreSQL和PostGIS的方法”的完整攻略:

1. 安装PostgreSQL

1.1 添加PostgreSQL Repository

通过以下命令添加PostgreSQL 9.6 Repository:

sudo yum install https://download.postgresql.org/pub/repos/yum/9.6/redhat/rhel-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm

1.2 安装PostgreSQL

使用以下命令安装PostgreSQL:

sudo yum install postgresql96-server

1.3 初始化数据库

使用以下命令初始化数据库:

sudo /usr/pgsql-9.6/bin/postgresql96-setup initdb

1.4 启动PostgreSQL

使用以下命令启动PostgreSQL:

sudo systemctl start postgresql-9.6

1.5 设置开机自启动

使用以下命令设置PostgreSQL开机自启动:

sudo systemctl enable postgresql-9.6

2. 安装 PostGIS

2.1 添加PostGIS Repository

通过以下命令添加PostGIS Repository:

sudo rpm -ivh http://yum.postgresql.org/9.6/redhat/rhel-7-x86_64/pgdg-centos96-9.6-3.noarch.rpm

2.2 安装 PostGIS

使用以下命令安装PostGIS:

sudo yum install postgis2_96

2.3 创建模板数据库

使用以下命令创建模板数据库,这里以模板库名为template_postgis_20为例:

sudo su postgres
createdb template_postgis_20
psql -d template_postgis_20 -c "CREATE EXTENSION postgis;"
psql -d template_postgis_20 -c "CREATE EXTENSION postgis_topology;"
psql -d template_postgis_20 -c "GRANT ALL ON geometry_columns TO PUBLIC;"
psql -d template_postgis_20 -c "GRANT ALL ON geography_columns TO PUBLIC;"
psql -d template_postgis_20 -c "GRANT ALL ON spatial_ref_sys TO PUBLIC;"

2.4 设置为默认模板数据库

使用以下命令设置模板数据库为默认模板数据库:

sudo su postgres
psql -d postgres -c "UPDATE pg_database SET datistemplate='true' WHERE datname='template_postgis_20';"

2.5 安装完成

安装完成,可以使用PostGIS了。

以下是两条示例说明:

  • 示例1:创建一个名字为test的PostgreSQL数据库,并使用PostGIS扩展:
sudo su postgres
createdb test
psql -d test -c "CREATE EXTENSION postgis;"
psql -d test -c "CREATE EXTENSION postgis_topology;"
  • 示例2:在新建的数据库中导入一个shapefile,并在地图上显示
sudo dnf install wget unzip
wget https://download.geofabrik.de/asia/china-latest-free.shp.zip
unzip china-latest-free.shp.zip
sudo shp2pgsql -s 4326 -I -W "GBK" china-latest-free.shp public.china | sudo psql -d test

好了,以上就是“CentOS7使用yum安装PostgreSQL和PostGIS的方法”的完整攻略。