我试图在将新数据添加到数据库时调用一个函数。
NpgsqlConnection connListenRun = new NpgsqlConnection("Server=main;Port=5432;Database=netdb;UserId=postgres;Password=password;");
try
{
connListenRun.Open();
NpgsqlCommand cmd = new NpgsqlCommand("listen RunLogClient;", connListenRun);
cmd.ExecuteNonQuery();
connListenRun.Notification += new NotificationEventHandler(RunFinishNotification);
}
catch (NpgsqlException ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
//connListen.Close();
}
private void RunFinishNotification(object sender, NpgsqlNotificationEventArgs e)
{
MessageBox.Show("Data!");
}
但是,添加新数据时我的消息框没有显示。在使用相同触发函数的另一个程序上具有“ SyncNotification = true;”在conListenRun的末尾。
NpgsqlConnection connListenRun = new NpgsqlConnection("Server=main;Port=5432;Database=netdb;UserId=postgres;Password=password;SyncNotification=true;");
但是,当我输入“ SyncNotification = true;”时在陈述中我得到这个错误:
:'不支持关键字:同步通知 参数名称:关键字'
我在做什么错了?
谢谢
答案 0 :(得分:0)
我正在使用NPGSQL的最新版本3.6.2(我认为),而其他项目正在使用2.11.96版本。由于使用旧版本,因此该程序可以运行。我猜较新的NPGSQL使用了不同的方式来执行触发函数。
答案 1 :(得分:0)
具有npgsql.dll版本的示例代码
知道这适用于3.2.6.0或从Postgres 10起的版本(这可能意味着从ngpsql.dll v3.0起)。
public static void Main(string[] args)
{
bool flag = true;
string server = "127.0.0.1";
string port = "5432";
string database = "postgres";
string uid = "postgres";
string password = "postgres";
string connStr;
// the connection string
connStr = $"SERVER = {server}; Port = {port}; DATABASE = {database}; User Id =
{uid}; PASSWORD = {password};";
NpgsqlConnection notificationConnection;
NpgsqlConnectionStringBuilder csb = new NpgsqlConnectionStringBuilder(connStr);
try
{
notificationConnection = new NpgsqlConnection(connStr);
notificationConnection.Open();
if (notificationConnection.State != System.Data.ConnectionState.Open)
{
WriteLine("Connection to database failed");
return;
}
using (NpgsqlCommand cmd = new NpgsqlCommand($"LISTEN {notificationName}",
notificationConnection))
{
cmd.ExecuteNonQuery();
}
notificationConnection.Notification += PostgresNotification;
notificationConnection.WaitAsync();
}
catch(Exception ex)
{
WriteLine($"Exception thrown with message : {ex.Message}");
return;
}
// wait forever, press enter key to exit program
ReadLine();
// stop the db notifcation
notificationConnection.Notification -= PostgresNotification;
using (var command = new NpgsqlCommand($"unlisten {notificationName}",
notificationConnection))
{
command.ExecuteNonQuery();
}
notificationConnection.Close();
}
// the callback method that handles notification
static void PostgresNotification(object sender, NpgsqlNotificationEventArgs e)
{
WriteLine("Notification Received");
}
答案 2 :(得分:0)
您缺少connconnListenRun.WaitAsync();
或connconnListenRun.Wait();