簡體   English   中英

有沒有比DataTable.Load(DataReader)填充數據表更快/更智能的方法? C#

[英]Is there a faster/smarter way, to fill a datatable than DataTable.Load(DataReader)? C#

我正在做一些研究,以便更好地理解SQL並使用DataTables。 所以我試圖從MS SQL數據庫中獲得良好的性能讀取數據並將其加載到datagridview中。

我已經創建了一個SQL函數,我從我的工具調用它並將結果加載到數據表中。 如果我在SSMS中執行此功能,則需要11-12秒來加載結果(差不多150萬個條目),但如果我使用該工具執行此功能,我編碼,則需要30秒以上(僅做DataTable.Load(SqlDataReader))

到目前為止我所做的是:

    private DataTable GetDataFromDB(string userId, string docId, DateTimeOffset date)
    {            
        string cmd = String.Format("select * from dbo.GetData(@userId, @docId, @dueDate);");

        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();

            SqlCommand command = new SqlCommand(cmd, conn);

            if (String.IsNullOrEmpty(userId))
                command.Parameters.AddWithValue("@userId", DBNull.Value);
            else
                command.Parameters.AddWithValue("@userId", userId);

            if (String.IsNullOrEmpty(docId))
                command.Parameters.AddWithValue("@docId", DBNull.Value);
            else
                command.Parameters.AddWithValue("@docId", docId);
            command.Parameters.AddWithValue("@dueDate", dueDate);

            SqlDataReader reader = command.ExecuteReader();

            stopWatch.Reset();
            stopWatch.Start();

            table.BeginLoadData();
            table.Load(reader, LoadOption.Upsert);
            table.EndLoadData();
            stopWatch.Stop();
            reader.Close();
            reader.Dispose();
            conn.Close();
        }

        return table;
    }

我已經做了一些谷歌研究,這是我能想到的最好的。 到目前為止它運作良好,但我很好奇是否有可能更快地獲得結果。 有任何想法嗎? 我的內存也有問題。 一旦我開始通話,該工具將分配高達900MB的RAM,直到它具有所有條目。 我已經管理過,每次調用上面的函數時都要釋放內存,但我認為,900MB是相當多的,另一個問題是,它不會釋放所有需要的RAM。 例如:當我啟動該工具時,它需要大約7MB的RAM,如果我第一次調用上面的方法,它將需要900MB。 如果我下次調用它,它將釋放大部分內存,但仍需要930MB。 第三次960MB等。 因此,每次調用它會分配更多的內存,這會導致“系統內存不足”-Exception,如果經常調用此方法。

非常感謝!

性能將根據您加載的數據量和數量而有所不同。 下面的鏈接將為您提供性能報告的解決方案。 用你的方法嘗試這樣的東西,並比較性能。

希望這會幫助你。

填充數據表的最快方法

對我來說,使用DataTable.Load(SqlDataReader)是最快的方法

        DataTable dt = new DataTable();
        using (var con = new SqlConnection { ConnectionString = "ConnectionString" })
        {
            using (var command = new SqlCommand { Connection = con })
            {
                con.Open();
                command.CommandText = @"SELECT statement.....";
                command.Parameters.AddWithValue("@param", "Param");
                //load the into DataTable
                dt.Load(command.ExecuteReader(), LoadOption.Upsert);
            }// this will dispose command

        }// this will dispose and close connection

暫無
暫無

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

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