天天看點

關于C#操作資料庫ExecuteNonQuery()的傳回值問題

1 if (AccessCon.ExecuteSql(sql = "select * from salesData where index ='" + man.Index + "'") > 0)
 2             {
 3                 retValue = AccessCon.ExecuteSql(sql = "update salesData set sellingPrize='" + man.SellingPrize + "' where index='" + man.Index + "'");
 4                 Console.WriteLine(sql);
 5             }
 6             else
 7             {
 8                 retValue = AccessCon.ExecuteSql(sql = "insert into salesData values ('" + man.Index + "','" + man.SellingPrize + "')");
 9                 Console.WriteLine(sql);
10             }
11 
12             return retValue;      

  本來想通過select * from salesData where index =' man.Index '執行後的傳回值是否大于0判斷表中是否已有資料

因為msdn中說傳回受影響的行數:

Executes a Transact-SQL statement against the connection and returns the number of rows affected.

但是卻沒看到備注裡說

For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.

對于UPDATE, INSERT,和 DELETE傳回受影響的函數,但是對于所有其他類型的語句,傳回值為 -1。如果發生復原,傳回值也為 -1。這樣對于search語句來說就不适合ExecuteNonQuery()方法了。

轉載于:https://www.cnblogs.com/20zhiyuxue/p/5880682.html