簡體   English   中英

事務,表截斷和參數化SQL查詢

[英]Transaction, Table Truncate and Parametrized SQL Query

我必須清除表中的所有內容並重新加載新數據。 有超過1500行,因此出於性能原因需要TRUNCATE TABLE

我的方法的流程是:

  1. 開始交易
  2. 截斷表格
  3. 獲取最新數據
  4. 使用SQL參數化值插入所有行
  5. 獲取數據&&插入成功? 提交事務:回滾

我的問題是:我可以使用SqlConnection成功執行上述操作嗎? 因為我正在截斷表並且基本上執行> 1500個插入,所以我有點猶豫是否只是為了找出而運行代碼。 我試過在網上看,雖然我發現了類似的問題,但我覺得它們並不是我的具體情況。

這是我為執行所需操作而開發的方法:

        public static void InsertCourseLookup(List<Course> courses)
        {
            using (SqlConnection connection = new SqlConnection(ConnectionString))
            {
                connection.Open();

                using (SqlCommand command = connection.CreateCommand())
                {
                    SqlTransaction transaction = connection.BeginTransaction("CourseLookupTransaction");

                    command.Connection = connection;
                    command.Transaction = transaction;
                    command.CommandTimeout = 300;

                    try
                    {
                        command.CommandText = "TRUNCATE TABLE course_info";
                        command.ExecuteNonQuery();

                        foreach (Course course in courses)
                        {
                            if (course == null)
                            {
                                throw new ArgumentException("course cannot be null");
                            }

                            ContentData courseData = GlobalHelper.GetContentData(course.ContentId);

                            if (courseData == null)
                            {
                                throw new Exception(string.Format("Missng ContentData for course '{0}'", course.Title));
                            }
                            // checks if row is already in table, if it is check.ContentId will be greater than 0
                            CourseLookup check = CourseHelper.GetCourseLookup(course.DatabaseId);

                            string sql = string.Empty;

                            if (check.ContentID > 0)
                            {
                                sql = @"
                                    UPDATE  course_info
                                    SET     content_id = @content_id,
                                            name = @name,
                                            code = @code,
                                            description = @description,
                                            url = @url,
                                            meta_keywords = @meta_keywords,
                                            meta_description = @meta_description
                                    WHERE   course_id = @course_id";
                            }
                            else
                            {
                                sql = @"
                                    INSERT INTO course_info(course_id, content_id, name, code, description, url, meta_keywords, meta_description)
                                    VALUES(@course_id, @content_id, @name, @code, @description, @url, @meta_keywords, @meta_description)";
                            }

                            string metaKeywords = string.Empty;
                            string metaDescription = string.Empty;

                            if (courseData.MetaData != null)
                            {
                                for (int i = 0; i < courseData.MetaData.Length; i++)
                                {
                                    if (courseData.MetaData[i].Id == ConfigData.Metadata.MetaKeywordsID)
                                    {
                                        metaKeywords = DataHelper.TruncateString(courseData.MetaData[i].Text, 500);
                                    }
                                    else if (courseData.MetaData[i].Id == ConfigData.Metadata.MetaDescriptionID)
                                    {
                                        metaDescription = DataHelper.TruncateString(courseData.MetaData[i].Text, 500);
                                    }
                                }
                            }

                            command.CommandText = sql;
                            command.Parameters.AddRange(
                                new SqlParameter[] {
                                    new SqlParameter("@course_id", course.DatabaseId),
                                    new SqlParameter("@content_id", course.ContentId),
                                    new SqlParameter("@name", course.Title),
                                    new SqlParameter("@code", course.Code),
                                    new SqlParameter("@description", course.Description),
                                    new SqlParameter("@url", courseData.Quicklink),
                                    new SqlParameter("@meta_keywords", metaKeywords),
                                    new SqlParameter("@meta_description", metaDescription)
                                }
                            );
                            command.ExecuteNonQuery();
                            command.Parameters.Clear();
                        }

                        transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        Log.Error(string.Format("Unable to reload course lookup table: {0}", ex.Message));
                    }

                }
            }
        }

這將有效阻止任何錯誤。

您應該將事務放在using塊中並刪除它:

catch (Exception ex)
{
    transaction.Rollback();
    Log.Error(string.Format("Unable to reload course lookup table: {0}", ex.Message));
}

因為這沒什么。

注意,截斷表需要使用模式修改鎖和混合快照讀取器。 DELETE FROM MyTable不會這樣做。 它允許並發(讀取)訪問。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM