如果Sql Server返回錯誤,則應拋出SqlException。但事實並非如此

[英]If Sql Server returns an error, then SqlException should be thrown. But it isn't



If I bind GridView to SqlDataSource and also set AutoGenerateEditButton to true, and if I then try to update a field ( this field being a primary key in database ), then database should return an error and thus SqlException should be thrown?! So why doesn’t page report an exception? Instead, all Gridview does is setting all fields in that row back to their original values.

如果我將GridView綁定到SqlDataSource並將AutoGenerateEditButton設置為true,如果我然后嘗試更新字段(此字段是數據庫中的主鍵),那么數據庫應該返回錯誤,因此應該拋出SqlException?!那么為什么頁面報告異常呢?相反,所有Gridview都會將該行中的所有字段設置回原始值。


thanx


EDIT:

Hello,


When I executed same update statement with the following code, I got Cannot update identity column 'EmployeeID' exception, so I’m assuming Sql Server did report same error when GridView tried to update, but for some reason exception wasn't raised:

當我使用以下代碼執行相同的更新語句時,我得到了無法更新標識列'EmployeeID'異常,因此我假設當GridView嘗試更新時,Sql Server確實報告了相同的錯誤,但由於某種原因,未引發異常:

        SqlConnection sc = new SqlConnection();
        sc.ConnectionString = @"Data source=localhost; integrated security=sspi; initial catalog=northwind;";
        SqlCommand sComand = new SqlCommand();

        sComand.Connection = sc;
        sComand.CommandText = "update Employees set EmployeeId=100,FirstName='Suzy',"+ 
                   "LastName='Smile',City='Moon' where EmployeeId=1";
        sc.Open();
        int I = sComand.ExecuteNonQuery();


SECOND EDIT:

Is your DataKeyNames property set correctly?

您的DataKeyNames屬性是否設置正確?

I tried with setting DataKeyNames="EmployeeId", but exception was still not raised

我嘗試設置DataKeyNames =“EmployeeId”,但仍然沒有引發異常

4 个解决方案

#1


If your SQL query returns a result, then C# will get that result. If your SQL query throws an exception, then C# will get that exception. You cannot mix and match here, it's not a wardrobe.

如果您的SQL查詢返回結果,那么C#將獲得該結果。如果您的SQL查詢拋出異常,那么C#將獲得該異常。你不能在這里混搭,它不是衣櫥。

#2


An exception will be thrown ONLY if the ERROR severity in T-SQL is 16 or higher AFAIK. So not all errors are the same in SQL Server.

僅當T-SQL中的ERROR嚴重性為16或更高AFAIK時,才會拋出異常。因此,並非SQL Server中的所有錯誤都相同。

#3


You should actually be able to modify the primary key without error, so long as it doesn't result in a duplicate.

實際上,您應該能夠無錯誤地修改主鍵,只要它不會導致重復。

#4


Is your DataKeyNames property set correctly?

您的DataKeyNames屬性是否設置正確?


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2009/04/08/72a061a8d17d753d812751fec1f40dd4.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com