使用Groovy脚本通过sql条件语句的查询结果,将一台MySQL服务器上的数据同步到另一台MySQL服务器
时间: 2024-04-30 22:24:07 浏览: 104
上。
1. 连接源数据库和目标数据库
使用Groovy中的Sql类,分别连接源数据库和目标数据库:
```groovy
def sourceUrl = 'jdbc:mysql://source-host:3306/source-db'
def sourceUsername = 'source-username'
def sourcePassword = 'source-password'
def sourceSql = Sql.newInstance(sourceUrl, sourceUsername, sourcePassword, 'com.mysql.jdbc.Driver')
def targetUrl = 'jdbc:mysql://target-host:3306/target-db'
def targetUsername = 'target-username'
def targetPassword = 'target-password'
def targetSql = Sql.newInstance(targetUrl, targetUsername, targetPassword, 'com.mysql.jdbc.Driver')
```
2. 查询源数据库的数据
使用Sql类的execute方法执行查询语句,获取需要同步的数据:
```groovy
def sql = 'SELECT * FROM table WHERE condition = ?'
def condition = 'value'
def result = sourceSql.rows(sql, [condition])
```
3. 同步数据到目标数据库
遍历查询结果,使用Sql类的execute方法执行插入语句,将数据同步到目标数据库:
```groovy
result.each { row ->
def insertSql = 'INSERT INTO table (col1, col2, col3) VALUES (?, ?, ?)'
targetSql.execute(insertSql, [row.col1, row.col2, row.col3])
}
```
完整的同步脚本如下:
```groovy
def sourceUrl = 'jdbc:mysql://source-host:3306/source-db'
def sourceUsername = 'source-username'
def sourcePassword = 'source-password'
def sourceSql = Sql.newInstance(sourceUrl, sourceUsername, sourcePassword, 'com.mysql.jdbc.Driver')
def targetUrl = 'jdbc:mysql://target-host:3306/target-db'
def targetUsername = 'target-username'
def targetPassword = 'target-password'
def targetSql = Sql.newInstance(targetUrl, targetUsername, targetPassword, 'com.mysql.jdbc.Driver')
def sql = 'SELECT * FROM table WHERE condition = ?'
def condition = 'value'
def result = sourceSql.rows(sql, [condition])
result.each { row ->
def insertSql = 'INSERT INTO table (col1, col2, col3) VALUES (?, ?, ?)'
targetSql.execute(insertSql, [row.col1, row.col2, row.col3])
}
sourceSql.close()
targetSql.close()
```
阅读全文