1. 程式人生 > >DataTable的資料批量寫入資料庫

DataTable的資料批量寫入資料庫

最近在將excel中的檔案匯入到資料庫中,用程式進行編寫,由於資料量較大所以速度很慢,後來採用了SqlBulkCopy類,解決了速度的問題,我就insert語句,sqldataadapter.update(dataset,tablename);sqlbulkcopy.WriteToServer(datatable);三個方法的效能進行比較:

1、生成測試的datatable表,表結構如下

UniqueID(主鍵,自動增長)  |  CompanyName  |  CompanyCode  |  Address  |  Owner  |  Memo

共6個欄位。

 SqlConnection sqlconnection = new SqlConnection(connectionString);
 SqlDataAdapter sqldataadapter = new SqlDataAdapter("select * from Table_1 where 1=2", sqlconnection);
 DataSet dataset = new DataSet();
 sqldataadapter.Fill(dataset, "Table_1");
 DataTable datatable = dataset.Tables[0];
  //生成20000條記錄

  for (int i = 0; i < 20000; i++)
  {
          DataRow datarow = datatable.NewRow();
          datarow["CompanyName"] = "companyname"+string.Format("{0:0000}",i);
          datarow["CompanyCode"] = "companycode" + string.Format("{0:0000}", i);
          datarow["Address"] = "address" + string.Format("{0:0000}", i);
          datarow["Owner"] = "owner" + string.Format("{0:0000}", i);
          datarow["Memo"] = "memo" + string.Format("{0:0000}", i);

          datatable.Rows.Add(datarow); 
  }

2、使用sqlcommand.executenonquery()方法插入

foreach (DataRow datarow in datatable.Rows)
{
string sql = "INSERT INTO [Table_1]

([CompanyName],[CompanyCode],[Address],[Owner],[Memo])" +
"VALUES('" + datarow["CompanyName"].ToString() + "'" +
",'" + datarow["CompanyCode"].ToString() + "'" +
",'" + datarow["Address"].ToString() + "'" +
",'" + datarow["Owner"].ToString() + "'" +
",'" + datarow["Memo"].ToString() + "')";
  using (SqlConnection sqlconn = new SqlConnection(connectionString))
  {
      sqlconn.Open();

      SqlCommand sqlcommand = new SqlCommand(sql, sqlconn);
      sqlcommand.ExecuteNonQuery();
      sqlconn.Close();
  }
}

插入20000條記錄時間:00:00:29.7336000

3、使用sqldataadapter.update(dataset,tablename);

SqlCommand insertcommand = new SqlCommand("INSERT INTO [Table_1]([CompanyName],[CompanyCode],[Address],[Owner],[Memo])" +
 "VALUES(@CompanyName, @CompanyCode,@Address,@Owner,@Memo)",new SqlConnection(connectionString));
 insertcommand.Parameters.Add("@CompanyName", SqlDbType.NChar, 50, "CompanyName");
 insertcommand.Parameters.Add("@CompanyCode", SqlDbType.NChar, 25, "CompanyCode");
insertcommand.Parameters.Add("@Address", SqlDbType.NChar, 255, "Address");
insertcommand.Parameters.Add("@Owner", SqlDbType.NChar, 25, "Owner");
insertcommand.Parameters.Add("@Memo", SqlDbType.NChar, 255, "Memo");
sqldataadapter.InsertCommand = insertcommand;

sqldataadapter.Update(dataset, "Table_1");   

插入20000條記錄時間:00:00:22.8938000

4、使用sqlbulkcopy.writetoserver(datatable)

SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.UseInternalTransaction);
sqlbulkcopy.DestinationTableName = "Table_1";//資料庫中的表名

sqlbulkcopy.WriteToServer(dataset.Tables[0]);

插入20000條記錄時間:00:00:00.3276000

所以說速度是sqlbulkcopy最快,sqldataadapter.update()次之,sqlcommand.ExecuteNonQuery()最慢。

測試結果