.Net中大量新增資料的幾種實現方法比較

來源:互聯網
上載者:User

標籤:des   datagridview   style   blog   http   color   io   os   ar   

在.Net中經常會遇到大量新增資料,如將Excel中的資料匯入資料庫,直接在DataGridView控制項中添加資料再儲存到資料庫等等。

方法一:一條一條迴圈添加

通常我們的第一反應是採用for或foreach迴圈一條一條的添加。

for (int i = 0; i < dgv.Rows.Count; i++){    string sql  = "insert into .....";    SqlHelper.ExcuteNonQuery(CommandType.Text, sql, null);}

這樣的方法可想而知,效率肯定很低,可以慢到操作人員無法接受的那種。經過測試(區域網路),1W條資料將會耗時3分42秒842毫秒

方法二:每一千條迴圈添加

也許馬上會有人想到Insert多條記錄,即"Insert into TableName Values(‘ ‘,‘ ‘,‘ ‘),Values(‘ ‘,‘ ‘,‘ ‘)",這種方法在一定程度上提高不少的效率,但是這種方法有幾個弊端。比如說,在SQL Server 2000中它就不支援這種文法,會提示"第 2 行: ‘,‘ 附近有語法錯誤。"的警告,大量操作也就無從談起。再比如,這種方法麼次最多也只能Insert 1000條資料,如果超過了1000條就會報錯:"INSERT 語句中行值運算式的數目超出了 1000 行值的最大允許值。"。當然了,我們可以分為幾次,每次添加一千條資料,這樣還是比方法一的效率高不少。經過測試(區域網路),1W條資料將會耗時0分14秒766毫秒

int rowCount = dataGridView1.Rows.Count;int quotient = rowCount / 1000;  //商int remainder = rowCount % 1000;  //餘數StringBuilder str = new StringBuilder();         for (int j = 0; j < quotient; j++){    str.Append("insert into BatchTable values");    for (int i = 0; i < 1000; i++)    {        str.AppendFormat("(‘{0}‘,‘{1}‘,‘{2}‘,‘{3}‘,‘{4}‘,‘{5}‘,‘{6}‘,‘{7}‘,‘{8}‘,‘{9}‘,‘{10}‘),"            , dataGridView1[0, i].Value, dataGridView1[1, i].Value, dataGridView1[2, i].Value, dataGridView1[3, i].Value,            dataGridView1[4, i].Value , dataGridView1[5, i].Value, dataGridView1[6, i].Value, dataGridView1[7, i].Value,             dataGridView1[8, i].Value, dataGridView1[9, i].Value, dataGridView1[10, i].Value);    }     string sql = str.ToString().TrimEnd(‘,‘);    SqlHelper.ExcuteNonQuery(CommandType.Text, sql, null);    str.Clear();}if (remainder > 0){    str.Append("insert into BatchTable values");    for (int i = 0; i < remainder; i++)    {        str.AppendFormat("(‘{0}‘,‘{1}‘,‘{2}‘,‘{3}‘,‘{4}‘,‘{5}‘,‘{6}‘,‘{7}‘,‘{8}‘,‘{9}‘,‘{10}‘),"            , dataGridView1[0, i].Value, dataGridView1[1, i].Value, dataGridView1[2, i].Value, dataGridView1[3, i].Value             , dataGridView1[4, i].Value, dataGridView1[5, i].Value, dataGridView1[6, i].Value, dataGridView1[7, i].Value,            dataGridView1[8, i].Value, dataGridView1[9, i].Value, dataGridView1[10, i].Value);    }    string sql = str.ToString().TrimEnd(‘,‘);    SqlHelper.ExcuteNonQuery(CommandType.Text, sql, null);    str.Clear();}

 

方法三:使用SqlBulkCopy類大量新增資料

SqlBulkCopy類位於System.Data.SqlClient命名空間下,摘自MSDN:Microsoft SQL Server 提供一個稱為 bcp 的流行的命令提示字元工具 + 生產力,用於將資料從一個表移動到另一個表(表既可以在同一個伺服器上,也可以在不同伺服器上)。SqlBulkCopy 類允許編寫提供類似功能的Managed 程式碼解決方案。還有其他將資料載入到 SQL Server 表的方法(例如 INSERT 語句),但相比之下SqlBulkCopy 提供明顯的效能優勢。使用 SqlBulkCopy 類只能向 SQL Server 表寫入資料。但是,資料來源不限於 SQL Server;可以使用任何資料來源,只要資料可載入到 DataTable 執行個體或可使用IDataReader 執行個體讀取資料。

採用 SqlBulkCopy類進行大量新增資料將會大大調高效率。經過測試(區域網路),1W條資料將會耗時0分0秒292毫秒

public static bool ExcuteNonQuery(DataTable dt){    SqlConnection connection = new SqlConnection(connString);    connection.Open();    SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(connection);    sqlbulkcopy.BulkCopyTimeout = 100;  //逾時之前操作完成所允許的秒數    sqlbulkcopy.BatchSize = dt.Rows.Count;  //每一批次中的行數    sqlbulkcopy.DestinationTableName = dt.TableName;  //伺服器上目標表的名稱    for (int i = 0; i < dt.Columns.Count; i++)    {        sqlbulkcopy.ColumnMappings.Add(i, i);  //映射定義資料來源中的列和目標表中的列之間的關係    }    sqlbulkcopy.WriteToServer(dt);  // 將DataTable資料上傳到資料表中    connection.Close();    return true;}

 

.Net中大量新增資料的幾種實現方法比較

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.