データ ソースのデータの更新

適用対象: .NET Framework .NET .NET Standard

ADO.NET のダウンロード

データを変更する SQL ステートメント ( INSERT、 UPDATE、 DELETEなど) は行を返しません。 同様に、多くのストアド プロシージャは、アクションを実行しても行を返しません。 行を返さないコマンドを実行するには、適切な SQL コマンドを使用して Command オブジェクトを作成し、必要な Parameters を含む Connection を作成します。 ExecuteNonQuery オブジェクトの SqlCommand メソッドでコマンドを実行します。

ExecuteNonQuery メソッドからは、実行されたステートメントまたはストアド プロシージャの影響を受けた行数を表す整数が返されます。 複数のステートメントが実行された場合は、実行された各ステートメントの影響を受けたレコードの合計を示す値が返されます。

次のコード例では、INSERT を使用してデータベースにレコードを挿入する ステートメントを実行します。

// Assumes connection is a valid SqlConnection.
connection.Open();

string queryString = "INSERT INTO Customers " +
"(CustomerID, CompanyName) Values('NWIND', 'Northwind Traders')";

SqlCommand command = new SqlCommand(queryString, connection);
Int32 recordsAffected = command.ExecuteNonQuery();

カタログ操作の実行」と同じコードで作成されたストアド プロシージャを実行するコードの例を次に示します。 ストアド プロシージャは行を返さないため ExecuteNonQuery メソッドが使用されていますが、ストアド プロシージャは入力パラメーターを受け取り、出力パラメーターと戻り値を返します。

// Assumes command is a valid SqlCommand with an open connection.
command.CommandText = "InsertCategory";
command.CommandType = CommandType.StoredProcedure;

SqlParameter parameter = command.Parameters.Add("@RowCount", SqlDbType.Int);
parameter.Direction = ParameterDirection.ReturnValue;

parameter = command.Parameters.Add("@CategoryName", SqlDbType.NChar, 15);

parameter = command.Parameters.Add("@Identity", SqlDbType.Int);
parameter.Direction = ParameterDirection.Output;

command.Parameters["@CategoryName"].Value = "New Category";
command.ExecuteNonQuery();

Int32 categoryID = (Int32) command.Parameters["@Identity"].Value;
Int32 rowCount = (Int32) command.Parameters["@RowCount"].Value;

関連項目