GroovyによるJDBC操作


package groovy

import groovy.sql.Sql
import com.mysql.jdbc.Driver
/**
 * @author Leon
 *
 */
public class DataBase{
	public static void main(def args){
		//     
		def sql= Sql.newInstance("jdbc:mysql://localhost:3306/groovy","root","1234",
		"org.gjt.mm.mysql.Driver")
		
		def db= new DataBase();		
		
		//          false
		//println db.delete(sql);

		def word=db.netset(sql);//     
		//        - :     
		//word.add("username":"newname");
		//     
		word.each{
			//  username     
			println it.username;
			//      hello            			 
			if(it.username=="hello"){				
				println it.getAt(-3);
			}
		}
		
	}
	//  
	def select(sql){
		//        
		sql.eachRow("select * from user"){
			println it.username;
		}
	}			
	//  
	def insert(sql){
		sql.execute("insert into user(username,password) values('hello','kitty')");
	}
	//  
	def delete(sql){
		sql.execute("delete from user where row_id=4");
	}
	//  
	def update(sql){
		sql.executeUpdate("update user set password='213456' where row_id=2");
	}
	//   
	def netset(sql){
		sql.dataSet("user");
	}
}