首批通过分布式安全可靠测评,为关键业务系统打造
通过 Liquibase 管理 OcenBase 数据库版本
更新时间:2026-04-14 14:16:46
Liquibase 是一个开源的数据库版本控制工具,它支持数据库 Schema 的版本追踪、更新以及回滚。
前提条件
- 您已安装 OceanBase 数据库并且创建了 MySQL 模式租户。
版本兼容性
建议使用 OceanBase 的 V4.2.3 或更高版本,以确保更好的集成体验。
操作步骤
步骤一:获取数据库连接串
联系 OceanBase 数据库部署人员或者管理员获取相应的数据库连接串,例如:
obclient -h$host -P$port -u$user_name -p$password -D$database_name
参数说明:
$host:提供 OceanBase 数据库连接 IP。OceanBase 数据库代理(OceanBase Database Proxy,ODP)连接方式使用的是一个 ODP 地址;直连方式使用的是 OBServer 节点的 IP 地址。$port:提供 OceanBase 数据库连接端口。ODP 连接的方式默认是2883,在部署 ODP 时可自定义;直连方式默认是2881,在部署 OceanBase 数据库时可自定义。$database_name:需要访问的数据库名称。注意
连接租户的用户需要拥有该数据库的
CREATE、INSERT、DROP和SELECT权限。更多有关用户权限的信息,请参见 MySQL 模式下的权限分类。user_name:格式为 用户@租户#集群名称 或 用户名@SERVICE:服务名。使用格式 用户@租户#集群名称 时,默认租户为 'sys',管理员用户为 'root'。直连数据库时可省略集群名称,ODP 连接时则需要填写。$password:提供账户密码。
更多连接串的信息,请参见 通过 OBClient 连接 OceanBase 租户。
示例如下:
obclient -hxxx.xxx.xxx.xxx -P2881 -utest_user001@mysql001 -p****** -Dtest
步骤二:使用 Liquibase 的参考示例
将 JDBC 驱动放入 Liquibase 的 lib 目录下
在您的虚拟机中,找到您解压的 Liquibase 文件夹,进入
lib目录。将下载的mysql-connector-j-x.x.x.jar文件复制到此目录下。或使用命令行:
mv path/to/mysql-connector-j-x.x.x.jar path/to/liquibase/lib/新建配置文件
在 Liquibase 的根目录下,新建一个名为
liquibase.properties的配置文件。您可以使用任意文本编辑器(如nano、vim或gedit)创建该文件,写入以下内容:url: jdbc:mysql://xxx.xxx.xxx.xxx:2881/test username: your_username password: your_password classpath: lib/mysql-connector-j-8.3.0.jar请确保替换
xxx.xxx.xxx.xxx为您的 OceanBase 数据库主机地址,以及输入您的数据库端口号、用户名和密码。获取数据库地址、端口号、用户名和密码参见步骤一。生成数据库当前结构状态的快照
切换到 Liquibase 的根目录并执行以下命令,生成当前数据库结构的快照:
./liquibase --changeLogFile=mydatabase_changelog.xml generateChangeLog根据您使用的 Liquibase 版本,实际参数可能会有所不同,请参考 Liquibase 官方文档。
创建新的表
在 Liquibase 的根目录下,新建一个名为
dbchangelog.xml的文件,写入以下内容:<?xml version="1.0" encoding="UTF-8"?> <databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:pro="http://www.liquibase.org/xml/ns/pro" xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-4.4.xsd http://www.liquibase.org/xml/ns/pro http://www.liquibase.org/xml/ns/pro/liquibase-pro-4.5.xsd"> <changeSet author="BobR" id="myIDNumber123"> <createTable tableName="actor"> <column autoIncrement="true" name="id" type="INTEGER"> <constraints nullable="false" primaryKey="true" primaryKeyName="actor_pkey"/> </column> <column name="firstname" type="VARCHAR(255)"/> <column name="lastname" type="VARCHAR(255)"/> <column name="twitter" type="VARCHAR(15)"/> </createTable> </changeSet> </databaseChangeLog>执行变更
使用以下命令执行变更,创建
actor表:./liquibase update --changeLogFile=dbchangelog.xml回滚操作
变更成功后,您也可以尝试执行回滚操作,将数据库回退到上一个版本:
./liquibase rollbackCount 1 --changelog-file=dbchangelog.xml
更多信息
如果在使用 Liquibase 的过程中遇到问题,建议您查阅 Liquibase 官方文档。