一、前言(升级原因)

  1. 旧版本:PostgreSQL 9.2(2013年,已停止维护)
  2. 报错:不支持 CREATE INDEX IF NOT EXISTSADD COLUMN IF NOT EXISTS
  3. 目标版本:PostgreSQL 15.8(稳定版、现代语法全支持)
  4. 系统:CentOS 7 x86_64

二、【重要】升级前全量备份

1. 切换 postgres 用户备份(解决权限问题)

su - postgres

2. 执行备份(数据库名:zilu)

pg_dump zilu -Fc -f /var/lib/pgsql/backup_zilu_before_upgrade.dump

3. 退出用户

exit

4. 验证备份文件(确保生成)

ls -lh /var/lib/pgsql/backup_zilu_before_upgrade.dump

出现文件即备份成功!


三、清理旧源 + 安装 PostgreSQL 15

1. 清理失效 yum 源

yum install -y yum-utils
yum-config-manager --disable pgdg12 pgdg13 pgdg14 pgdg15
yum clean all
rm -rf /var/cache/yum

2. 安装 PG15 依赖包

yum install -y https://mirrors.aliyun.com/postgresql/repos/yum/15/redhat/rhel-7-x86_64/postgresql15-15.8-1PGDG.rhel7.x86_64.rpm https://mirrors.aliyun.com/postgresql/repos/yum/15/redhat/rhel-7-x86_64/postgresql15-libs-15.8-1PGDG.rhel7.x86_64.rpm

3. 安装 PG15 服务端

yum install -y https://mirrors.aliyun.com/postgresql/repos/yum/15/redhat/rhel-7-x86_64/postgresql15-server-15.8-1PGDG.rhel7.x86_64.rpm https://mirrors.aliyun.com/postgresql/repos/yum/15/redhat/rhel-7-x86_64/postgresql15-contrib-15.8-1PGDG.rhel7.x86_64.rpm

4. 初始化数据库

/usr/pgsql-15/bin/postgresql-15-setup initdb

5. 启动并开机自启

systemctl start postgresql-15
systemctl enable postgresql-15

6. 验证版本

su - postgres -c "/usr/pgsql-15/bin/psql -c 'SELECT version();'"

显示 PostgreSQL 15.8 安装成功!


四、创建 zilu 数据库(SpringBoot 用)

su - postgres -c "/usr/pgsql-15/bin/psql -c 'CREATE DATABASE zilu;'"

查看数据库

su - postgres -c "/usr/pgsql-15/bin/psql -c '\l'"

五、恢复备份数据(关键步骤)

su - postgres -c "/usr/pgsql-15/bin/pg_restore -d zilu /var/lib/pgsql/backup_zilu_before_upgrade.dump"

六、配置密码 + 远程连接

1. 设置 postgres 密码

su - postgres -c "/usr/pgsql-15/bin/psql -c \"ALTER USER postgres WITH PASSWORD 'password1234..';\""

2. 开启远程访问

sed -i 's/#listen_addresses = '\''localhost'\''/listen_addresses = '\''*'\''/' /var/lib/pgsql/15/data/postgresql.conf
echo "host    all             all             0.0.0.0/0               md5" >> /var/lib/pgsql/15/data/pg_hba.conf

3. 重启生效

systemctl restart postgresql-15

4. 开放 5432 端口

firewall-cmd --permanent --add-port=5432/tcp
firewall-cmd --reload

七、SpringBoot 连接配置(application.yml)

spring:
  datasource:
    url: jdbc:postgresql://你的地址:5432/zilu
    username: postgres
    password: password1234..
    driver-class-name: org.postgresql.Driver

八、最终连接测试

PGPASSWORD='password1234..' /usr/pgsql-15/bin/psql -U postgres -d zilu -h 127.0.0.1 -c 'SELECT 1;'

九、数据库信息汇总(可直接复制到文章)

内容
数据库版本 PostgreSQL 15.8
服务器IP
端口 5432
数据库名 zilu
用户名 postgres
密码 password1234…
备份文件路径 /var/lib/pgsql/backup_zilu_before_upgrade.dump

十、升级成功效果

  1. 数据完整无损(备份+恢复)
  2. ✅ 支持 CREATE INDEX IF NOT EXISTS
  3. ✅ 支持 CREATE TABLE IF NOT EXISTS
  4. ✅ SpringBoot 完美连接
  5. ✅ 远程连接正常
  6. ✅ 旧版本语法报错全部消失

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐