数据库相关-Spock
Spock连接数据库
import com.alibaba.fastjson.JSON
import com.google.common.reflect.TypeToken
import com.meituan.mtrace.Tracer
import com.sankuai.solarsystem.aigc.common.util.GsonUtil
import com.sankuai.solarsystem.aigc.domain.assistant.extension.AssistantApplicationService
import com.sankuai.solarsystem.aigc.domain.assistant.model.AssistantAppInfoModel
import com.sankuai.solarsystem.aigc.flow.business.botmigrate.BotManageService
import com.sankuai.solarsystem.aigc.flow.dto.business.botmigrate.BotInfoSyncExecuteRecordDTO
import groovy.sql.Sql
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.web.WebAppConfiguration
import spock.lang.Requires
import spock.lang.Specification
import spock.lang.UnrollSql sql;def setup() {def dbUrl = "jdbc:mysql://ip:port/dbName"def user = "rds_zjj"def password = "xxxxxx"def driver = "com.mysql.jdbc.Driver"sql = Sql.newInstance(dbUrl, user, password, driver)}def "数据库查询测试"() {given: "配置数据库连接"sqlwhen: "执行数据库查询"def result = this.sql.rows('select * from application_scene where id= ?', ['454'])log.info("result : {}", JSON.toJSONString(result))then: "验证查询结果"assert result.size() > 0cleanup: "关闭数据库连接"sql.close()}
从GroovyRowResult中获取查询结果
// 使用GroovyRowResult获取查询结果中的值def "GroovyRowResult 获取值示例"() {given: "已经执行了数据库查询,得到了GroovyRowResult列表"// 假设这是从数据库查询返回的结果列表List<GroovyRowResult> results = [[id: 1, name: '张三', age: 30],[id: 2, name: '李四', age: 25]]when: "从GroovyRowResult中获取特定的值"// 获取第一个结果的name值def firstName = results[0].name// 获取第二个结果的age值def secondAge = results[1].agethen: "验证获取的值是否符合预期"assert firstName == '张三'assert secondAge == 25
}