在ADO.NET有一个概念就是事件,所谓的事件就是发生的一次动作,文章这里就ADO.NET连接事件和大家深入细则的谈谈。所有 .NET Framework 数据提供程序中的 Connection 对象有两个事件,可用于从数据源中检索信息性消息或确定 Connection 的状态是否已被更改。 下表描述 Connection 对象的这些事件。
InfoMessage ADO.NET连接事件接收 SqlInfoMessageEventArgs 对象,该对象在其 Errors 属性中包含来自数据源的消息的集合。 您可以查询此集合中的 Error 对象,以获取错误编号和消息文本以及错误的来源。 SQL Server .NET Framework 数据提供程序还包含有关消息所来自的数据库、存储过程和行号的详细信息。
示例
以下代码示例显示如何为 InfoMessage 事件添加事件处理程序。
Visual Basic
- ' 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
C#
- // 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);
- }