Molet

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

Molet linux 2023-02-27 1208浏览 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);
            }
        }

 

继续浏览有关 数据库技术文章/教程 的文章
发表评论