0

抱歉这个可能很愚蠢的问题。由于我在互联网上没有发现任何关于它的信息,它可能非常明显,我只是盲目地看到?!

我正在尝试通过 DataAdapter.Update(dataset) 从数据集中更新数据库中的表

但是没有设置连接的可能性,DA 应该使用。

DA 在哪里知道如何连接到 DB?还是我误解了数据适配器的概念?

我目前的代码是这样的:

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;
}

我刚写了这个并且开始怀疑它是如何(或是否)工作的......到目前为止我还没有测试过它,因为我必须编写一些其他代码才能正确测试它

谢谢大家,StackOverflow FTW!

4

1 回答 1

5

SqlDataAdapter 需要接受一个 SqlCommand 对象,该对象有一个与之绑定的 SqlConnection 对象。这几乎就是层次结构分解的方式。

至于你如何去做,有一些选项可以将它们传递给构造函数,以及在构造之后设置各种属性。

这是一篇msdn 文章,其中包含选择、插入、更新和删除的示例。

自由贸易协定:

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;
}
于 2009-06-24T12:09:47.270 回答