SqlException 类

定义

SQL Server 返回警告或错误时引发的异常。The exception that is thrown when SQL Server returns a warning or error. 此类不能被继承。This class cannot be inherited.

public ref class SqlException sealed : System::Data::Common::DbException
[System.Serializable]
public sealed class SqlException : System.Data.Common.DbException
type SqlException = class
    inherit DbException
Public NotInheritable Class SqlException
Inherits DbException
继承
属性

示例

下面的示例生成SqlException , 并显示异常。The following example generates a SqlException and then displays the exception.

public static void ShowSqlException(string connectionString)
{
    string queryString = "EXECUTE NonExistantStoredProcedure";
    StringBuilder errorMessages = new StringBuilder();
    
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(queryString, connection);
        try
        {
            command.Connection.Open();
            command.ExecuteNonQuery();
        }
        catch (SqlException ex)
        {
            for (int i = 0; i < ex.Errors.Count; i++)
            {
                errorMessages.Append("Index #" + i + "\n" +
                    "Message: " + ex.Errors[i].Message + "\n" +
                    "LineNumber: " + ex.Errors[i].LineNumber + "\n" +
                    "Source: " + ex.Errors[i].Source + "\n" +
                    "Procedure: " + ex.Errors[i].Procedure + "\n");
            }
            Console.WriteLine(errorMessages.ToString());
        }
    }
}
Public Sub ShowSqlException(ByVal connectionString As String)
    Dim queryString As String = "EXECUTE NonExistantStoredProcedure"
    Dim errorMessages As New StringBuilder()

    Using connection As New SqlConnection(connectionString)
        Dim command As New SqlCommand(queryString, connection)

        Try
            command.Connection.Open()
            command.ExecuteNonQuery()

        Catch ex As SqlException
            Dim i As Integer
            For i = 0 To ex.Errors.Count - 1
                errorMessages.Append("Index #" & i.ToString() & ControlChars.NewLine _
                    & "Message: " & ex.Errors(i).Message & ControlChars.NewLine _
                    & "LineNumber: " & ex.Errors(i).LineNumber & ControlChars.NewLine _
                    & "Source: " & ex.Errors(i).Source & ControlChars.NewLine _
                    & "Procedure: " & ex.Errors(i).Procedure & ControlChars.NewLine)
            Next i
            Console.WriteLine(errorMessages.ToString())
        End Try
    End Using
End Sub

注解

每当用于 SQL Server 的 .NET Framework 数据提供程序遇到服务器生成的错误时, 就会创建此类。This class is created whenever the .NET Framework Data Provider for SQL Server encounters an error generated from the server. (客户端错误作为标准公共语言运行时异常引发。)始终至少包含一个SqlError实例。 SqlException(Client side errors are thrown as standard common language runtime exceptions.) SqlException always contains at least one instance of SqlError.

严重级别为10或更低的消息为信息性消息, 并指示用户输入的信息中的错误导致的问题。Messages that have a severity level of 10 or less are informational and indicate problems caused by mistakes in information that a user has entered. 严重级别为11到16的是用户生成的, 并可由用户更正。Severity levels from 11 through 16 are generated by the user, and can be corrected by the user. 严重级别为 17 到 25 的消息指示存在软件或硬件错误。Severity levels from 17 through 25 indicate software or hardware errors. 如果发生级别为17、18或19的错误, 您可以继续工作, 不过您可能无法执行特定语句。When a level 17, 18, or 19 error occurs, you can continue working, although you might not be able to execute a particular statement.

当严重级别为 19 或以下时,SqlConnection 将保持打开状态。The SqlConnection remains open when the severity level is 19 or less. 当严重性级别为20或更大时, 服务器通常会关闭SqlConnectionWhen the severity level is 20 or greater, the server ordinarily closes the SqlConnection. 但是,用户可以重新打开连接并继续操作。However, the user can reopen the connection and continue. 最后两种情况下,执行该命令的方法将生成 SqlExceptionIn both cases, a SqlException is generated by the method executing the command.

有关 SQL Server 发送的警告和信息性消息的信息, 请参阅数据库引擎事件和错误For information about the warning and informational messages sent by SQL Server, see Database Engine Events and Errors. SqlException类映射到 SQL Server 严重性。The SqlException class maps to SQL Server severity.

下面是有关如何处理异常的一般信息。The following is general information on handling exceptions. 你的代码应该捕获异常, 以防止应用程序崩溃, 并允许向用户显示相关错误消息。Your code should catch exceptions to prevent the application from crashing and to allow displaying a relevant error message to the user. 无论客户端应用程序中发生的情况 (包括故障) 如何, 都可以使用数据库事务来确保数据的一致性。You can use database transactions to ensure that the data is consistent regardless of what happens in the client application (including a crash). 诸如 BeginTransaction 或方法 (在 OleDbConnection、ODBCConnection 和 SqlClient 中) 等功能将确保一致的数据, 而无需考虑异常情况的情况。由提供程序引发。Features like System.Transaction.TransactionScope or the BeginTransaction method (in System.Data.OleDb.OleDbConnection, System.Data.ODBC.ODBCConnection, and System.Data.SqlClient.SqlConnection) ensure consistent data regardless of exceptions raised by a provider. 事务可能会失败, 因此捕获失败, 并重试该事务。Transactions can fail, so catch failures and retry the transaction.

请注意, 从 .NET Framework 4.5 开始SqlException , 可以返回内部Win32ExceptionNote that beginning with .NET Framework 4.5, SqlException can return an inner Win32Exception.

.NET Framework 数据提供程序的异常类报告特定于提供程序的错误。The exception class of a .NET Framework data provider reports provider-specific errors. 例如, System.data.odbc.odbcexception 具有 System.data.oledb.oledbexception, 而 SqlClient 具有 SqlException, 则为, 为。For example System.Data.Odbc has OdbcException, System.Data.OleDb has OleDbException, and System.Data.SqlClient has SqlException. 有关错误详细信息的最佳级别, 请捕获这些异常并使用这些异常类的成员来获取错误的详细信息。For the best level of error detail, catch these exceptions and use the members of these exception classes to get details of the error.

除了特定于提供程序的错误外, .NET Framework 数据访问接口类型还可以引发 .NET Framework 异常, 如 OutOfMemoryException 和 ThreadAbortException。In addition to the provider-specific errors, .NET Framework data provider types can raise .NET Framework exceptions such as System.OutOfMemoryException and System.Threading.ThreadAbortException. 可能无法从这些异常中恢复。Recovery from these exceptions may not be possible.

输入错误可能导致 .NET Framework 数据提供程序类型引发异常, 如 ArgumentException 或 IndexOutOfRangeException。Bad input can cause a .NET Framework data provider type to raise an exception such as System.ArgumentException or System.IndexOutOfRangeException. 在错误的时间调用方法可能会引发 InvalidOperationException。Calling a method at the wrong time can raise System.InvalidOperationException.

因此, 一般而言, 编写一个异常处理程序, 该处理程序可捕获来自公共语言运行时的任何特定于提供程序的异常以及异常。So, in general, write an exception handler that catches any provider specific exceptions as well as exceptions from the common language runtime. 可按如下所示分层:These can be layered as follows:

try {  
   // code here  
}  
catch (SqlException odbcEx) {  
   // Handle more specific SqlException exception here.  
}  
catch (Exception ex) {  
   // Handle generic ones here.  
}  
  

或者:Or:

try {  
   // code here  
}  
catch (Exception ex) {  
   if (ex is SqlException) {  
      // Handle more specific SqlException exception here.  
   }  
   else {  
      // Handle generic ones here.  
   }  
}  
  

在堆栈上没有用户代码的线程池线程上, .NET Framework 的数据提供程序方法调用也可能失败。It is also possible for a .NET Framework data provider method call to fail on a thread pool thread with no user code on the stack. 在这种情况下, 和使用异步方法调用时, 必须注册UnhandledException事件来处理这些异常并避免应用程序崩溃。In this case, and when using asynchronous method calls, you must register the UnhandledException event to handle those exceptions and avoid application crash.

属性

Class

获取从 SQL Server .NET Framework 数据提供程序返回的错误的严重级别。Gets the severity level of the error returned from the .NET Framework Data Provider for SQL Server.

ClientConnectionId

表示客户端连接 ID。Represents the client connection ID. 有关详细信息,请参阅 ADO.NET 中的数据跟踪For more information, see Data Tracing in ADO.NET.

Data

获取提供有关异常的其他用户定义信息的键/值对集合。Gets a collection of key/value pairs that provide additional user-defined information about the exception.

(继承自 Exception)
Errors

获取由一个或多个 SqlError 对象组成的集合,这些对象提供有关 SQL Server .NET Framework 数据提供程序所生成的异常的详细信息。Gets a collection of one or more SqlError objects that give detailed information about exceptions generated by the .NET Framework Data Provider for SQL Server.

HelpLink

获取或设置指向与此异常关联的帮助文件链接。Gets or sets a link to the help file associated with this exception.

(继承自 Exception)
HResult

获取或设置 HRESULT(一个分配给特定异常的编码数字值)。Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.

(继承自 Exception)
InnerException

获取导致当前异常的 Exception 实例。Gets the Exception instance that caused the current exception.

(继承自 Exception)
LineNumber

获取生成错误的 Transact-SQL 批命令或存储过程内的行号。Gets the line number within the Transact-SQL command batch or stored procedure that generated the error.

Message

获取对错误进行描述的文本。Gets the text describing the error.

Number

获取一个标识错误类型的数字。Gets a number that identifies the type of error.

Procedure

获取生成错误的存储过程或远程过程调用 (RPC) 的名称。Gets the name of the stored procedure or remote procedure call (RPC) that generated the error.

Server

获取正在运行生成错误的 SQL Server 实例的计算机的名称。Gets the name of the computer that is running an instance of SQL Server that generated the error.

Source

获取生成错误的提供程序的名称。Gets the name of the provider that generated the error.

StackTrace

获取调用堆栈上的即时框架字符串表示形式。Gets a string representation of the immediate frames on the call stack.

(继承自 Exception)
State

从 SQL Server 中获取一个数值错误代码,它表示错误、警告或“未找到数据”消息。Gets a numeric error code from SQL Server that represents an error, warning or "no data found" message. 有关如何将这些值解码的更多信息,请参阅数据库引擎事件和错误For more information about how to decode these values, see Database Engine Events and Errors.

TargetSite

获取引发当前异常的方法。Gets the method that throws the current exception.

(继承自 Exception)

方法

Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
GetBaseException()

当在派生类中重写时,返回 Exception,它是一个或多个并发的异常的根源。When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.

(继承自 Exception)
GetHashCode()

用作默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetObjectData(SerializationInfo, StreamingContext)

使用关于异常的信息设置 SerializationInfoSets the SerializationInfo with information about the exception.

GetType()

获取当前实例的运行时类型。Gets the runtime type of the current instance.

(继承自 Exception)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
ToString()

返回表示当前 SqlException 对象的字符串,并包括客户端连接 ID(有关更多信息,请参见 ClientConnectionId)。Returns a string that represents the current SqlException object, and includes the client connection ID (for more information, see ClientConnectionId).

事件

SerializeObjectState

当异常被序列化用来创建包含有关该异常的徐列出数据的异常状态对象时会出现该问题。Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception.

(继承自 Exception)

适用于

另请参阅