码迷,mamicode.com
首页 > 数据库 > 详细

执行多条SQL语句,实现数据库事务。(Oracle数据库)

时间:2015-09-23 08:56:29      阅读:282      评论:0      收藏:0      [点我收藏+]

标签:

    
        /// <summary>
        /// 执行多条SQL语句,实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">(key为sql语句,value是该语句的OracleParameter[])</param>
        /// <returns></returns>
        public static bool ExecuteSqlTran(Dictionary<string, object> SQLStringList)
        {        
            using (OracleConnection conn = new OracleConnection(connectionString))
            {
                conn.Open();
                using (OracleTransaction trans = conn.BeginTransaction()) 
                {
                    OracleCommand cmd = new OracleCommand();
                    try 
                    {
                        //循环
                        foreach (var myDE in SQLStringList)
                        {    
                            string cmdText=myDE.Key.ToString();
                            OracleParameter[] cmdParms=(OracleParameter[])myDE.Value;
                            PrepareCommand(cmd,conn,trans,cmdText, cmdParms);
                            int val = cmd.ExecuteNonQuery();
                            cmd.Parameters.Clear();
                        }
                        trans.Commit();
                        return true;
                    }
                    catch 
                    {
                        trans.Rollback();
                        return false;
                    }
                }                
            }
        }



 

        /// <summary>
        /// 配置命令对象
        /// </summary>
        /// <param name="cmd">命令对象</param>
        /// <param name="conn">连接对象</param>
        /// <param name="trans">事务对象</param>
        /// <param name="cmdText">sql语句</param>
        /// <param name="cmdParms">参数</param>
        private static void PrepareCommand(OracleCommand cmd, OracleConnection conn, OracleTransaction trans, string cmdText, OracleParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null)
                cmd.Transaction = trans;
            cmd.CommandType = CommandType.Text;//cmdType;
            if (cmdParms != null)
            {
                foreach (OracleParameter parm in cmdParms)
                    cmd.Parameters.Add(parm);
            }
        }

 

执行多条SQL语句,实现数据库事务。(Oracle数据库)

标签:

原文地址:http://www.cnblogs.com/bweb/p/4831164.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!