2017-02-17 4 views
1

Я пытаюсь написать скрипт GroovySQL, который будет иметь три разные переменные Arraylist. A1 [1,2,3], А2 [4,5,6], A3 [7,8,9].GroovySql: Как обновить таблицу переменными Arraylist

Я хочу, чтобы обновить таблицу таким образом, что три ряда из трех столбцов таблицы обновлений как
данных должны быть (в строке стрелки)
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]) 

мне удалось узнать, как обновить одну строку. Я буду благодарен, если кто-нибудь может дать какие-либо намеки или идеи.

+0

Почему это помечено Java? Я предлагаю использовать «groovy» и «groovy-sql». – Axel

ответ

1

Все, что вам нужно сделать, это создать массив 2d и перенести его, а затем выполнить запрос обновления путем его петли.

Вот сценарий:

//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

Смежные вопросы