C# & SQL Server : inserting/update only truly executes when debugging

前端 未结 2 1365
执念已碎
执念已碎 2021-01-23 18:07

I have a rather simplistic API for adding, and then later updating a small table in SQL Server. It will insert (or update, which exhibits the same odd behavior) when I step into

2条回答
  •  隐瞒了意图╮
    2021-01-23 19:02

    BeginExecuteNonQuery() is an asynchronous method. It will return immediately, before the command is executed. To wait for it to complete, use EndExecuteNonQuery method.

    When you call BeginExecuteNonQuery to execute a Transact-SQL statement, you must call EndExecuteNonQuery in order to complete the operation. If the process of executing the command has not yet finished, this method blocks until the operation is complete.

    It seems you're looking for synchronous method. If that's the case, simply use

    sqlCmd.ExecuteNonQuery();
    

    This one will return only after the command is executed.

    If you want to execute the command asynchronously, it's much easier to use the ExecuteNonQueryAsync method.

    await sqlCmd.ExecuteNonQueryAsync();
    

    Note that you will have to make your method async to use await. You also need .NET 4.5+ to use it.

提交回复
热议问题