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

    
        /// <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);
            }
        }

 

posted @ 2015-09-23 08:40  石中隐鱼  阅读(1798)  评论(0编辑  收藏  举报