2017-02-17 7 views
1

3つの異なるArraylist変数を持つGroovySQLスクリプトを作成しようとしています。 A1 [1,2,3]、A2 [4,5,6]、A3 [7,8,9]である。 1,4,7-
R2:2GroovySql:Arraylist変数を使用してテーブルを更新する方法

私はテーブルの3列の3列(賢い行で)でなければならない
データとして更新
R1になるようにテーブルを更新します、5,8
R3:3,6,9私は1つの行を更新する方法を知っている管理

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

ためtim_yates

enter image description here

クレジット?私は 'groovy'と 'groovy-sql'を使うことをお勧めします。 – Axel

答えて

1

2次元配列を作成して転置し、ループスルーで更新クエリを実行するだけです。ここで

はスクリプトです:

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

あなたはクエリは下回っで構築されてどのように表示されることがあります。これは、Javaをタグ付けされるのはなぜtranspose matrix

関連する問題