---
title: "直接使用groovy的sql来直接进行DB操作"
author: "乐溪925"
date: "2010-10-09T11:23:17Z"
tags: ["Bean", "Grails", "Groovy", "SQL", "Spring"]
categories: ["企业架构"]
slug: "groovy-sql-db"
draft: false
lastmod: "2010-10-09T15:49:15Z"
id: 779346
url: "https://jcsuper.iteye.com/blog/779346"
---

特殊的需求，在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
    }

}