C# 使用对 DataTable 所做的更改更新数据库...混淆
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15273057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Update database with changes made to DataTable... confusion
提问by Jimmy D
If I fill a DataTable with DataAdapter.Fill(DataTable);
and then make changes to a row in the DataTable with something simple like this: DataTable.Rows[0]["Name"] = "New Name";
how can I easily save those changes back to the database? I assumed I could call DataAdapter.Update(DataTable);
but I read that only works with a TableAdapter(?).
如果我填充一个数据表,DataAdapter.Fill(DataTable);
然后使用这样的简单操作对数据表中的一行进行更改:DataTable.Rows[0]["Name"] = "New Name";
如何轻松地将这些更改保存回数据库?我以为我可以打电话,DataAdapter.Update(DataTable);
但我读到它只适用于 TableAdapter(?)。
回答by Jimmy D
Here is an actual helpful answer in case anyone else needs to know how to do this:
这是一个实际有用的答案,以防其他人需要知道如何执行此操作:
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);
回答by Syed Fahad Ali
Take note of SqlBulkCopyOptions.KeepIdentity , you may or may not want to use this for your situation.
请注意 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);
}