groovy学习7-groovy sql

发现groovy操作数据库很简单,一行import,2行操作代码。

 

 

ContractedBlock.gif ExpandedBlockStart.gif 代码
 
   
import groovy.sql.Sql

/* *
* @author <a href="mailto:zhangting@taobao.com">张挺</a>
* @since 2010-4-2 15:07:35
*
*/
piEstimate
= 3 ;
println(
" Pi is about ${piEstimate} " );
println(
" Pi is closer to ${22 / 7} " );

// 使用Sql对象查询
//
第一个it是普通的对象应用,第二个it是groovy表达式
sql = Sql.newInstance( " jdbc:mysql://localhost:3306/test " , " root " ,
" xxxxxxx " , " com.mysql.jdbc.Driver " )
sql.eachRow(
" select * from user " , { println it.id + " -- ${it.username} -- " });

// 取第一行
row = sql.firstRow( " select username, password from user " )
println
" Row: columnA = ${row.username} and columnB = ${row.password} "

// 执行插入
username = " yue "
password
= " O'shea "
sql.execute(
" insert into user (username, password) values (${username}, ${password}) " )


// another insert demo use prepareStatment
username = " yue "
password
= " wu "
sql.execute(
" insert into user (username, password) values (?,?) " , [username, password])

// 更新操作,也可以用sql.execute("update user set password = ? where id=?", [comment,4])
comment = " test "
sql.executeUpdate(
" update user set password = ? where id=? " , [comment, 4 ])

// delete
sql.execute( " delete from word where word_id = ? " , [ 5 ])

// 在业务逻辑层就可以这么用直接返回list
def getPersons() {
def persons
= []
sql.eachRow(
" Select * from user " ) {
persons
<< it.toRowResult()
}
return persons
}

// 如果返回的类的属性和表明一致的话就可以这么做
Person p = new Person( it.toRowResult() )

 

 

 

转载于:https://www.cnblogs.com/xiziyin/archive/2010/04/02/1703280.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值