使用对DataTable所做的更改来更新数据库...混淆

时间:2013-03-07 13:56:48

标签: c# datatable dataadapter

如果我使用DataAdapter.Fill(DataTable);填充DataTable,然后使用以下简单的内容更改DataTable中的行:DataTable.Rows[0]["Name"] = "New Name";如何轻松地将这些更改保存回数据库?我以为我可以打电话给DataAdapter.Update(DataTable);,但我读到它只适用于TableAdapter(?)。

2 个答案:

答案 0 :(得分:25)

如果其他人需要知道如何执行此操作,这是一个实际有用的答案:

string selectStatement = "SELECT * FROM Contact";
System.Data.DataTable dt = new System.Data.DataTable();
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
conn.Open();
SqlDataAdapter sqlDa = new SqlDataAdapter();
sqlDa.SelectCommand = new SqlCommand(selectStatement, conn);
SqlCommandBuilder cb = new SqlCommandBuilder(sqlDa);
sqlDa.Fill(dt);
dt.Rows[0]["Name"] = "Some new data here";
sqlDa.UpdateCommand = cb.GetUpdateCommand();
sqlDa.Update(dt);

答案 1 :(得分:0)

记下SqlBulkCopyOptions.KeepIdentity,您可能想也可能不想在您的情况下使用它。

using (var bulkCopy = new SqlBulkCopy(_connection.ConnectionString, SqlBulkCopyOptions.KeepIdentity))
{
      // my DataTable column names match my SQL Column names, so I simply made this loop. However if your column names don't match, just pass in which datatable name matches the SQL column name in Column Mappings
      foreach (DataColumn col in table.Columns)
      {
          bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName);
      }
      bulkCopy.BulkCopyTimeout = 600;
      bulkCopy.DestinationTableName = destinationTableName;
      bulkCopy.WriteToServer(table);
}