使用数据集将大数据插入数据库

时间:2012-11-23 14:10:35

标签: c# insert dataset large-data

如何将数据集中的约300条记录插入数据库? 这需要5分钟左右 我想知道有没有办法改进使用数据集的过程?

编辑: 这是我的代码,当用户klik sav时,它将执行以下过程:

public void ProcessSkalaGaji(MyDataSet myDataSet, DateTime tanggalBerlaku, decimal percentage)
{
   GenerateNewSkalaGaji(myDataSet, tanggalBerlaku, percentage);
   InsertSkalaGaji(myDataSet);
}

private void GenerateNewSkalaGaji(MyDataSet myDataSet, DateTime tanggalBerlaku, decimal percentage)
{
   // GetLastSkalaGaji returns about 300 rows
   MyDataSet.SkalaGajiDataTable skalaGajiTable = GetLastSkalaGaji();

   foreach (MyDataSet.SkalaGajiRow skalaGajiRow in skalaGajiTable.Rows)
   {
      MyDataSet.SkalaGajiRow newSkalaGajiRow = myDataSet.SkalaGaji.NewSkalaGajiRow();
      newSkalaGajiRow.TanggalBerlaku = tanggalBerlaku;
      newSkalaGajiRow.Golongan = skalaGajiRow.Golongan;
      newSkalaGajiRow.MasaKerja = skalaGajiRow.MasaKerja;
      newSkalaGajiRow.GajiPokok = skalaGajiRow.GajiPokok + (skalaGajiRow.GajiPokok * percentage / 100);

      myDataSet.SkalaGaji.AddSkalaGajiRow(newSkalaGajiRow);
   }
}

private string InsertSkalaGaji(MyDataSet myDataSet)
{
   string errorMsg = string.Empty;

   if (myDataSet.HasChanges() && !myDataSet.HasErrors)
   {
      int rowsAffected = Adapter.Update(myDataSet.SkalaGaji);

      if (rowsAffected == 0)
      {
         errorMsg = "No rows inserted! Please contact your administrator";
      }
   }

   return errorMsg;
}

由于

2 个答案:

答案 0 :(得分:1)

您可以使用SqlBulkCopy类有效地将数据复制到数据库中。

var bulkCopy = new SqlBulkCopy(yourConnection);
bulkCopy.DestinationTableName = "dbo.YourTable";
var table = GetLastSkalaGaji();
bulkCopy.WriteToServer(table);

答案 1 :(得分:0)

我刚刚找到解决方案,当方法InsertSkalaGaji调用时,在Adapter.Update(myDataSet.SkalaGaji)之前我创建了一个只包含插入行的新SkalaGajiDataTable

代码:

MyDataSet.SkalaGajiDataTable newSkalaGaji = (MyDataSet.SkalaGajiDataTable)
myDataSet.SkalaGaji.GetChanges(DataRowState.Added);

int rowsAffected = Adapter.Update(newSkalaGaji);

并插入约300条记录,只需4秒钟 谢谢大家