DataAdapter.Fill(DataTable);
如果我用这样的简单方法填充 DataTable,然后对 DataTable 中的一行进行更改:DataTable.Rows[0]["Name"] = "New Name";
如何轻松地将这些更改保存回数据库?我以为我可以打电话DataAdapter.Update(DataTable);
,但我读到它只适用于 TableAdapter(?)。
问问题
33015 次
2 回答
33
这是一个实际有用的答案,以防其他人需要知道如何执行此操作:
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);
于 2013-03-08T12:26:11.937 回答
-1
请注意 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);
}
于 2015-05-05T20:44:48.433 回答