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