0

おそらくばかげた質問で申し訳ありません。私はそれについてインターネット上で何も見つけられなかったので、それはおそらく完全に明らかであり、私は見るのを盲目にしています?!

DataAdapter.Update(dataset) を介してデータセットからデータベース内のテーブルを更新しようとしています

ただし、接続を設定する可能性はありません。DA が使用する必要があります。

DA は DB への接続方法をどこで知っていますか? または、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;
}

これを書いたばかりで、それがどのように機能するか (または機能するかどうか) が疑わしくなりました...適切にテストする前に他のコードを書かなければならないので、これまでのところテストしていません。

ありがとうございました、StackOverflow FTW!

4

1 に答える 1

5

SqlDataAdapter は、SqlConnection オブジェクトが関連付けられている SqlCommand オブジェクトを取り込む必要があります。ヒエラルキーが崩壊するのは、まさにそのようなものです。

それをどのように行うかについては、それらをコンストラクターに渡すためのオプションと、構築後にさまざまなプロパティを設定するためのオプションがあります。

これは、選択、挿入、更新、および削除の例を含む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;
}
于 2009-06-24T12:09:47.270 に答える