对不起这个可能很愚蠢的问题.由于我在互联网上没有发现它,它可能是非常明显的,我只是盲目地看到了?!
我正在尝试通过DataAdapter.Update(数据集)从数据集更新数据库中的表
但是没有可能设置连接,DA应该使用.
DA在哪里知道如何连接到数据库?或者我是否误解了dataadapter的概念?
我目前的代码是这样的:
protected DataSet UpdateDataSet(DataSet ds) { DataSet dsChanges = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(); dsChanges = ds.GetChanges(); //Update DataSet da.Update(dsChanges); ds.Merge(dsChanges); return ds; }
我只是写了这个并且变得多可疑它是如何(或者如果)它的工作原理...我到目前为止还没有测试过它,因为我必须先编写一些其他的代码才能正确测试它
谢谢ppl,StackOVerflow FTW!
SqlDataAdapter需要接受一个SqlCommand对象,该对象具有绑定到它的SqlConnection对象.这几乎是层次结构崩溃的原因.
至于如何你去这样做,也有将它们传递到构造,以及设置施工后的各种属性选项.
这是一篇msdn文章,其中包含选择,插入,更新和删除的示例.
FTA:
public static SqlDataAdapter CreateCustomerAdapter( SqlConnection connection) { SqlDataAdapter adapter = new SqlDataAdapter(); // Create the SelectCommand. SqlCommand command = new SqlCommand("SELECT * FROM Customers " + "WHERE Country = @Country AND City = @City", connection); // Add the parameters for the SelectCommand. command.Parameters.Add("@Country", SqlDbType.NVarChar, 15); command.Parameters.Add("@City", SqlDbType.NVarChar, 15); adapter.SelectCommand = command; // Create the InsertCommand. command = new SqlCommand( "INSERT INTO Customers (CustomerID, CompanyName) " + "VALUES (@CustomerID, @CompanyName)", connection); // Add the parameters for the InsertCommand. command.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID"); command.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 40, "CompanyName"); adapter.InsertCommand = command; // Create the UpdateCommand. command = new SqlCommand( "UPDATE Customers SET CustomerID = @CustomerID, " + "CompanyName = @CompanyName " + "WHERE CustomerID = @oldCustomerID", connection); // Add the parameters for the UpdateCommand. command.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID"); command.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 40, "CompanyName"); SqlParameter parameter = command.Parameters.Add( "@oldCustomerID", SqlDbType.NChar, 5, "CustomerID"); parameter.SourceVersion = DataRowVersion.Original; adapter.UpdateCommand = command; // Create the DeleteCommand. command = new SqlCommand( "DELETE FROM Customers WHERE CustomerID = @CustomerID", connection); // Add the parameters for the DeleteCommand. parameter = command.Parameters.Add( "@CustomerID", SqlDbType.NChar, 5, "CustomerID"); parameter.SourceVersion = DataRowVersion.Original; adapter.DeleteCommand = command; return adapter; }