mysql - GroovySQL : How to update a table with Arraylist variables

标签 mysql arraylist groovy groovy-sql

我正在尝试编写一个具有三个不同 Arraylist 变量的 GroovySQL 脚本。 A1[1,2,3],A2[4,5,6],A3[7,8,9].

我想更新表,使表的三列中的三行更新为
数据应该(按行)
R1: 1,4,7
R2: 2,5,8
R3: 3,6,9

def sql = Sql.newInstance("jdbc:mysql://localhost:3306/words", "Test",
           "test", "com.mysql.jdbc.Driver")
def nid = 1
def newupdate = "hello world"
sql.executeUpdate("update word set spelling = ? where word_id = ?", [ newupdate, nid])

我设法知道如何更新一行。如果有人能提供任何提示或想法,我将不胜感激。

最佳答案

您需要做的就是创建一个二维数组并将其转置,然后通过循环执行更新查询。

这是脚本:

//Defined the data that you mentioned
def A1 = [1,2,3]
def A2 = [4,5,6]
def A3 = [7,8,9]

//Chage here your column names that you want to update
//column_0 can be your in your where clause
def columnNames = ['column_0', 'column_1', 'column_2']

//2d array of above data
def matrix = [A1, A2, A3]

//Transpose it to change rows & columns
def transMatrix = (0..<(matrix*.size().max())).collect {
    matrix*.getAt(it)
}
println "Transposed matrix is ==> $transMatrix"



def sql = Sql.newInstance("jdbc:mysql://localhost:3306/words", "Test", "test", "com.mysql.jdbc.Driver")

//Loop thru transposed matrix,
//Build the query
//Pass it to executeUpdte
transMatrix.each { rowData ->
    def query = "update word set ${columnNames[1]} = '${rowData[1]}', ${columnNames[2]} = '${rowData[2]}' where ${columnNames[0]} = '${rowData[0]}'"
    println "Generated query is : ${query}"
    sql.executeUpdate(query)
}

您可能会在下面看到查​​询是如何构建的:

enter image description here

归功于 tim_yates对于transpose matrix

关于mysql - GroovySQL : How to update a table with Arraylist variables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42294903/

相关文章:

grails - 如何在Grails中的gsp上根据环境在Config.groovy中设置值并获得相同参数的不同值?

java - 如何知道mysql表中数据被更新(即数据删除、修改或插入),从而更新java中的json对象

php - mysql 返回一个 json 对象

mySQL转储不一致

java - 比较同一列表的两个列表元素之间的值

Groovy 反向映射键

php - Laravel 4.1 原始查询访问结果

java - 将特定项目从一个数组列表复制到另一个数组列表

java - 如何构造一个以Arraylist为参数的对象?

groovy - 原因:无此类属性:类org.gradle.api.plugins.Convention的sourceSets