---
title: "groovy datasource sql 在grails应用中如何处理事务 "
author: "seanwon"
date: "2009-03-31T18:53:19Z"
tags: []
categories: ["企业架构"]
slug: "groovy-datasource-sql-grails"
draft: false
lastmod: "2009-03-31T18:53:19Z"
id: 358526
url: "https://seanwon.iteye.com/blog/358526"
---

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

        *}*