博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

.net事务使用实例

Posted on 2010-08-26 14:12  moss_tan_jun  阅读(637)  评论(0编辑  收藏  举报

 

 

 #region 批量处理Sql
        /// <summary>
        /// 批量处理Sql
        /// </summary>
        /// <param name="Array_Sql"></param>
        /// <returns></returns>
        public static bool FileInsertToData(string[] Array_Sql)
        {
            bool  Result= true;

            SqlConnection sqlConn = new SqlConnection(strConn);
            SqlCommand Comm = sqlConn.CreateCommand();
            SqlTransaction myTrans;

            myTrans = sqlConn.BeginTransaction();

            Comm.Connection = sqlConn;
            Comm.Transaction = myTrans;
            Comm.CommandType = CommandType.Text;
            sqlConn.Open();
            try
            {
                for (int i = 0; i < Array_Sql.Length; i++)
                {
                    Comm.CommandText = Array_Sql[i].ToString();
                    Comm.ExecuteNonQuery();
                }
                myTrans.Commit();//事务提交
                Result = true;
            }
            catch (Exception ex)
            {
                myTrans.Rollback();//事务回滚
                Result = false;
            }
            finally
            {
                sqlConn.Close();
                Comm.Dispose();
            }

            return Result;

        }

        #endregion