groovy mysql_使用Groovy的sql模块操作mysql进行多种查询

本文介绍了如何使用Groovy的Sql模块连接并操作MySQL数据库,包括创建sql实例、执行查询以及不同方式处理查询结果。通过eachRow方法处理每行数据,支持元数据闭包显示,还演示了rows方法的不同用法,如传入参数进行查询。
摘要由CSDN通过智能技术生成

连接数据库,这里要创建一个sql实例来操作数据库,必须加载jdbc驱动包,使用两个注解,否则会报错:

import groovy.sql.Sql

url='jdbc:mysql://localhost:3307/test?useUnicode=true&characterEncoding=utf8'

driver='com.mysql.jdbc.Driver'

username='root'

passwd='123456'

//可以指定maven仓库

//@GrabResolver(name = 'aliyun', root = 'http://maven.aliyun.com/nexus/content/groups/public/')

//加载数据库连接驱动包

@Grab('mysql:mysql-connector-java:5.1.25')

@GrabConfig(systemClassLoader = true)

//创建sql实例

def sql = Sql.newInstance(url, username, passwd, driver)

查询:

eachRow: 对结果在闭包中进行处理:

sql.eachRow("select * from `user`") {

println it[0] //可以按表字段从左到右依次下标访问

println it.name //直接按字段名访问

}

//支持元数据闭包显示

sql.eachRow("select *

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
上。 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() ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值