简体   繁体   中英

Identify sql exception in c#?

how to catch sql exception with its error code(error no) to identify which exception is exactly thrown in c# ? for example database is offline or there is reference row in other table so sql wont allow me to delete row but how exactly i could identify what is the problem in catch so that i can display message to the user in my application

You need to put your database code into a try ... catch block, and (assuming you're using ADO.NET against SQL Server) then catch the SqlException .

try
{
   // your database code here
}
catch(SqlException sqlEx)
{ 
   foreach(SqlError error in sqlEx.Errors)
   {
       // you can inspect the individual errors, their code etc. here
   }
}

The SqlException object will contain a collection of SqlError objects that describe the error that happened in great detail - with line number, error code and everything.

Other databases will have similar constructs - check your docs!

在.net异常类层次结构中为每种类型的异常分配了特定的数字,您将在此处找到一些有用的资料

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM