public void ThrowSqlException()
{
string myConnString = "user id=sa;password=;database=northwind;server=badserver";
SqlConnection myConnection = new SqlConnection(myConnString);
try
{
myConnection.Open();
}
catch (SqlException e)
{
SqlErrorCollection myErrors = e.Errors;
Console.WriteLine("Class: {1}", e.Class);
Console.WriteLine("Error #{1}: {2} on line {3}.", e.Number, e.Message, e.LineNumber);
Console.WriteLine("Error reported by {1} while connected to {2}", e.Source, e.Server);
Console.WriteLine("Neither record was written to database.");
Console.WriteLine("Errors collection contains:"); for (int i=0; i < myErrors.Errors.Count; i++)
{
Console.WriteLine("Class: {1}", myErrors[i].Class);
Console.WriteLine("Error #{1}: {2} on line {3}.", myErrors[i].Number, myErrors[i].Message, myErrors[i].LineNumber);
Console.WriteLine("Error reported by {1} while connected to {2}", myErrors[i].Source, myErrors[i].Server);
}
}
}
具体请参见msdn,关于sqlException的帮助,
一般而言,sqlException,中,你可以用多个catch,或者用其返回的多个Number(用于代表错误的数字)进行处理!
{
string myConnString = "user id=sa;password=;database=northwind;server=badserver";
SqlConnection myConnection = new SqlConnection(myConnString);
try
{
myConnection.Open();
}
catch (SqlException e)
{
SqlErrorCollection myErrors = e.Errors;
Console.WriteLine("Class: {1}", e.Class);
Console.WriteLine("Error #{1}: {2} on line {3}.", e.Number, e.Message, e.LineNumber);
Console.WriteLine("Error reported by {1} while connected to {2}", e.Source, e.Server);
Console.WriteLine("Neither record was written to database.");
Console.WriteLine("Errors collection contains:"); for (int i=0; i < myErrors.Errors.Count; i++)
{
Console.WriteLine("Class: {1}", myErrors[i].Class);
Console.WriteLine("Error #{1}: {2} on line {3}.", myErrors[i].Number, myErrors[i].Message, myErrors[i].LineNumber);
Console.WriteLine("Error reported by {1} while connected to {2}", myErrors[i].Source, myErrors[i].Server);
}
}
}
具体请参见msdn,关于sqlException的帮助,
一般而言,sqlException,中,你可以用多个catch,或者用其返回的多个Number(用于代表错误的数字)进行处理!
{
//你的数据库操作代码
}
catch(Exception ex)
{
Response.Write(ex.Message+"<br>");//显示错误!
}
--------------------------------------------------------
HResult 获取或设置 HRESULT,它是分配给特定异常的编码数值。
{
//你的数据库操作代码
}
catch(SqlException ex)
{
Response.Write(ex.Number.ToString()+"<br>");//显示错误!
}
唯一索引 2607
08001 无法连接到数据源
08002 连接正在使用
08003 连接未打开
08004 数据源拒绝建立连接
08007 在执行事务的过程中连接失败
08S01 通讯链接失败 你可以参考一下Sql的联机帮助
{
dbManage.InsertRecord(myDataSet,isAuto); //插入数据
Response.Redirect ("ShowRecords.aspx?tbname=" + TableName,true);
}
catch (SqlException e1)
{
if (e1.Number == 2627) //duplicate primary key error
{
lblStatus.Text = "Error: A record with same ID already exists. Please use another ID.";
}
else
{
lblStatus.Text = "Error:" + e1.Number.ToString() + ", " + e1.Message;
}
}
catch (Exception ex)
{
lblStatus.Text = "Error occurs when trying to add a new record. Detail info is: " + ex.Message;
}其他的诸如外键冲突,约束等错误可以通过查看错误信息得到其 Number