连接事件Connection Events

所有 .NET Framework 数据提供程序都具有连接对象,这些对象包含两个事件,可用于从数据源检索信息性消息或确定连接的状态是否已更改。All of the .NET Framework data providers have Connection objects with two events that you can use to retrieve informational messages from a data source or to determine if the state of a Connection has changed. 下表描述了连接对象的事件。The following table describes the events of the Connection object.

EventEvent 描述Description
InfoMessageInfoMessage 当从数据源中返回信息性消息时发生。Occurs when an informational message is returned from a data source. 信息性消息是数据源中不会引发异常的消息。Informational messages are messages from a data source that do not result in an exception being thrown.
StateChangeStateChange 连接状态更改时发生。Occurs when the state of the Connection changes.

使用 InfoMessage 事件Working with the InfoMessage Event

您可以使用 InfoMessage 对象的 SqlConnection 事件从 SQL Server 数据源中检索警告和信息性消息。You can retrieve warnings and informational messages from a SQL Server data source using the InfoMessage event of the SqlConnection object. 从数据源返回的严重程度为 11 到 16 的错误将引发异常。Errors returned from the data source with a severity level of 11 through 16 cause an exception to be thrown. 但是,InfoMessage 事件可用于从数据源中获取与错误无关联的消息。However, the InfoMessage event can be used to obtain messages from the data source that are not associated with an error. 对于 Microsoft SQL Server,任何严重程度等于或小于 10 的错误都将被视为信息性消息,将使用 InfoMessage 事件来捕获。In the case of Microsoft SQL Server, any error with a severity of 10 or less is considered to be an informational message, and can be captured by using the InfoMessage event. 有关详细信息,请参阅数据库引擎错误严重级别 "一文。For more information, see the Database Engine Error Severities article.

InfoMessage事件接收一个SqlInfoMessageEventArgs对象,该对象包含数据源中的消息的集合,该对象在其错误属性中。The InfoMessage event receives an SqlInfoMessageEventArgs object containing, in its Errors property, a collection of the messages from the data source. 可以查询此集合中的错误对象以获取错误号和消息文本以及错误的源。You can query the Error objects in this collection for the error number and message text, as well as the source of the error. SQL Server .NET Framework 数据提供程序还包含有关消息所来自的数据库、存储过程和行号的详细信息。The .NET Framework Data Provider for SQL Server also includes detail about the database, stored procedure, and line number that the message came from.

示例Example

以下代码示例显示如何为 InfoMessage 事件添加事件处理程序。The following code example shows how to add an event handler for the InfoMessage event.

' Assumes that connection represents a SqlConnection object.  
  AddHandler connection.InfoMessage, _  
    New SqlInfoMessageEventHandler(AddressOf OnInfoMessage)  
  
Private Shared Sub OnInfoMessage(sender As Object, _  
  args As SqlInfoMessageEventArgs)  
  Dim err As SqlError  
  For Each err In args.Errors  
    Console.WriteLine("The {0} has received a severity {1}, _  
       state {2} error number {3}\n" & _  
      "on line {4} of procedure {5} on server {6}:\n{7}", _  
      err.Source, err.Class, err.State, err.Number, err.LineNumber, _  
    err.Procedure, err.Server, err.Message)  
  Next  
End Sub  
// Assumes that connection represents a SqlConnection object.  
  connection.InfoMessage +=   
    new SqlInfoMessageEventHandler(OnInfoMessage);  
  
protected static void OnInfoMessage(  
  object sender, SqlInfoMessageEventArgs args)  
{  
  foreach (SqlError err in args.Errors)  
  {  
    Console.WriteLine(  
  "The {0} has received a severity {1}, state {2} error number {3}\n" +  
  "on line {4} of procedure {5} on server {6}:\n{7}",  
   err.Source, err.Class, err.State, err.Number, err.LineNumber,   
   err.Procedure, err.Server, err.Message);  
  }  
}  

将错误作为信息性消息处理Handling Errors as InfoMessages

通常,只有从服务器发出的信息性消息和警告消息才会触发 InfoMessage 事件。The InfoMessage event will normally fire only for informational and warning messages that are sent from the server. 但是,当发生实际错误时,将停止执行启动服务器操作的ExecuteNonQueryExecuteReader方法,并引发异常。However, when an actual error occurs, the execution of the ExecuteNonQuery or ExecuteReader method that initiated the server operation is halted and an exception is thrown.

如果无论服务器生成任何错误都要继续处理命令中的语句的其他部分,请将 FireInfoMessageEventOnUserErrorsSqlConnection 属性设置为 trueIf you want to continue processing the rest of the statements in a command regardless of any errors produced by the server, set the FireInfoMessageEventOnUserErrors property of the SqlConnection to true. 这样做会使连接对错误触发 InfoMessage 事件,而不是引发异常并中断处理。Doing this causes the connection to fire the InfoMessage event for errors instead of throwing an exception and interrupting processing. 客户端应用程序可以处理此事件并对错误情况做出响应。The client application can then handle this event and respond to error conditions.

备注

严重程度等于或大于 17 的错误会造成服务器停止处理命令,这种错误必须作为异常来处理。An error with a severity level of 17 or above that causes the server to stop processing the command must be handled as an exception. 在这种情况下,无论如何在 InfoMessage 事件中处理该错误,都会引发异常。In this case, an exception is thrown regardless of how the error is handled in the InfoMessage event.

使用 StateChange 事件Working with the StateChange Event

连接的状态发生更改时, StateChange事件发生。The StateChange event occurs when the state of a Connection changes. StateChange事件StateChangeEventArgs接收,使你能够通过使用OriginalStateCurrentState属性来确定连接状态的更改。The StateChange event receives StateChangeEventArgs that enable you to determine the change in state of the Connection by using the OriginalState and CurrentState properties. OriginalState属性是一个ConnectionState枚举,指示连接在更改前的状态。The OriginalState property is a ConnectionState enumeration that indicates the state of the Connection before it changed. CurrentState是一个ConnectionState枚举,指示连接在更改后的状态。CurrentState is a ConnectionState enumeration that indicates the state of the Connection after it changed.

下面的代码示例使用StateChange事件在连接状态更改时将消息写入控制台。The following code example uses the StateChange event to write a message to the console when the state of the Connection changes.

' Assumes connection represents a SqlConnection object.  
  AddHandler connection.StateChange, _  
    New StateChangeEventHandler(AddressOf OnStateChange)  
  
Protected Shared Sub OnStateChange( _  
  sender As Object, args As StateChangeEventArgs)  
  
  Console.WriteLine( _  
  "The current Connection state has changed from {0} to {1}.", _  
  args.OriginalState, args.CurrentState)  
End Sub  
// Assumes connection represents a SqlConnection object.  
  connection.StateChange  += new StateChangeEventHandler(OnStateChange);  
  
protected static void OnStateChange(object sender,   
  StateChangeEventArgs args)  
{  
  Console.WriteLine(  
    "The current Connection state has changed from {0} to {1}.",  
      args.OriginalState, args.CurrentState);  
}  

请参阅See also