C#将侦听器附加到Npgsql连接

时间:2018-10-31 08:59:25

标签: c# postgresql npgsql

我正在用C#构建一个应用程序,该应用程序使用npgsql连接进行postgres数据库中的查询。我想知道是否有一种方法可以在查询执行的所有步骤中得到通知; 我的意思是我想接收消息:

  • “打开”:打开连接时
  • “正在连接”:连接正在连接时
  • “正在执行”:执行连接时
  • “关闭”:执行查询并关闭连接时

有办法吗?

2 个答案:

答案 0 :(得分:0)

您可以执行此操作,但是您必须自己触发通知。这是可行的,甚至很容易。在ADO.NET中,您的代码流类似于:

DbProviderFactory factory = DbProviderFactories.GetFactory("Npgsql");
using(DbConnection con = factory.CreateConnection()) 
{
      con.ConnectionString = ConfigurationManager.AppSettings[connectionName];
      con.Open();  
      // Connection is open, notify user
      DbCommand cmd = connection.CreateCommand();
      cmd.CommandText = query; 

      // Query execution is going to start, add code to inform user
      cmd.ExecuteXXX();
      // Query execution is done, add code to inform user
}

// the connection is closed - notify user

通知应该是异步的,以避免阻塞您可以通过事件实现的数据库代码。

答案 1 :(得分:0)

您是否要捕获StateChange事件?希望这会为您指明正确的方向。

    Dim csb = New NpgsqlConnectionStringBuilder(GetConnectionString(connectionName))
    csb.CommandTimeout = 0
    Using connection = New NpgsqlConnection(csb.ConnectionString)
        AddHandler connection.StateChange, AddressOf myHandler  ' <== This is where you specify the event Handler
        Using transaction = connection.BeginTransaction()
            ' Do your thing here.
            transaction.Commit()
        End Using
    End Using
End Sub


' This function will get called whenever the connection state changes.
Private Function myHandler(sender As Object, e As StateChangeEventArgs) As Object
    ' Do something here
End Function