trap of primary key error
i wants to trap sql-2000 primary key error into c# and develop my own error like "this is duplicate Invo开发者_Python百科ice Number"
kindly reply how to do this in c# application.
Thanx.
Generally, this is not considered good design. You should check for duplicate keys before inserting, and rely on DB constraints as a "safety net" only.
But if you feel like doing this, you need to catch the exception SQLException. Then you need to use SQLException's attribute (in particular ErrorCode and Number) to check to see if it is a PK violation.
But generally checking the exact reason of an SQLException is tricky and depends on the DBMS used, so it's not a nice and robust approach. That's one of the reasons why it's not recommended (see above).
Rather than handling it as an exception, if you expect it to happen, you should check to see if a particular ID exists prior to inserting it.
精彩评论