读书人

直接运用groovy的sql来直接进行DB操作

发布时间: 2012-09-12 09:21:30 作者: rapoo

直接使用groovy的sql来直接进行DB操作
特殊的需求,在GRAILS调用GROOVY SQL直接做数据更新、插入和删除,如何控制原子事务?



比较特殊的处理方案(如果有更好的方案,还请赐教)。

场景:SQL是用DATASOURCE创建的。

描述:因为设置是否自动提交是由CONNECTION处理的,但是直接用dataSource来创建,是没法得到connection的引用,所以必须用如下方式:



def dbTran = new groovy.sql.Sql(dataSource)
def con = dbTran.createConnection()
def db = new groovy.sql.Sql(con)

try{

con.autoCommit = false

db.execute("delete from rcbinfo")

db.insert.........

con.commit()

}catch(Exception e){

con.rollback()

}finally{

con.autoCommit = true

}








import groovy.sql.Sql

class MyFancySqlController {

def dataSource // the Spring-Bean "dataSource" is auto-injected

def list = {
def db = new Sql(dataSource) // Create a new instance of groovy.sql.Sql with the DB of the Grails app

def result = db.rows("SELECT foo, bar FROM my_view") // Perform the query

[ result: result ] // return the results as model
}

}

读书人网 >其他数据库

热点推荐