更新資料來源中的資料

適用於:.NET Framework .NET .NET Standard

下載 ADO.NET

會修改資料的 SQL 陳述式 (例如 INSERT、UPDATE 或 DELETE) 不會傳回資料列。 同樣地,許多預存程序會執行動作但不傳回資料列。 若要執行不會傳回資料列的命令,請使用適當的 SQL 命令與連線 (包含任何所需的參數) 來建立 Command 物件。 使用 SqlCommand 物件的 ExecuteNonQuery 方法來執行命令。

注意

ExecuteNonQuery 方法會傳回整數,其代表執行的陳述式或預存程序所影響的資料列數目。 如果執行多個陳述式,傳回的值就是受到所有執行的陳述式影響的記錄數總和。

範例

下列程式碼範例會使用 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;

請參閱