1. 程式人生 > >Groovy訪問oracle資料庫

Groovy訪問oracle資料庫

Groovy訪問資料庫,間接,方便。 需要提前將ojdbc5.jar放到groovy'的lib資料夾下面,或者確保你Groovy能去讀該驅動,例如-cp  .;xxx.jar;  等等

 import groovy.sql.Sql  
 import java.sql.Connection; 
 
  sql = Sql.newInstance(   
            "jdbc:oracle:thin:@xxxxxx:orcl",   
            "OR01",
            "OR01PW",
            "oracle.jdbc.driver.OracleDriver")   
    println("執行查詢語句");  
   //------------------------------------------------------------------------------
//-----從表-------------------------------------------------------------------------
sql.connection.autoCommit = false;

String insertSql = "INSERT INTO auth_token2(id, version, user2_id, token, expiration, description, os_user)"+
    " VALUES(?, 0, ?, ?, ?, ?, ?)"
String getOldTokenSql = "SELECT U.user2_id, AT.token, AT.expiration,"+
    " AT.description, UU.name FROM auth_token AT LEFT JOIN user U ON AT.user_id = U.id "
String deleteOldTokenSql = "DELETE FROM auth_token"

sql.eachRow(getOldTokenSql) { row ->
    String tokenId = UUID.randomUUID()
    String user2Id = row['user2_id']
    String token = row['token']
    def    expiration = row['expiration']    (該欄位為Long型別,可以刪除中文註釋)
    String desc = row['description']
    String name = row['name']
       
    sql.executeUpdate(insertSql, [tokenId, user2Id, token, expiration, desc, name])
    println "token ${token}"
}

sql.executeUpdate(deleteOldTokenSql);
sql.commit();