今天我写了以下代码,与名为Npgsql的PostgreSQL C#库配合使用:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Npgsql;
namespace PostgreSQLNotificationsTest
{
class Program
{
static void Main(string[] args)
{
using (var conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;User Id=postgres;Password=my_password;Database=helper_db.psql;SyncNotification=true"))
{
conn.Notification += OnNotification;
conn.Open();
using (var command = new NpgsqlCommand("listen notifytest;", conn))
{
command.ExecuteNonQuery();
}
Console.ReadLine();
};
}
private static void OnNotification(object sender, NpgsqlNotificationEventArgs e)
{
Console.WriteLine("event handled: " + e.AdditionalInformation);
}
}
}
然后我执行以下步骤:
注:以上内容为涉及IT技术的命令行操作。createdb.exe -h 127.0.0.1 -p 5432 -U postgres -W helper_db.psql
psql.exe -h 127.0.0.1 -p 5432 -U postgres -W helper_db.psql
create table helper(first text primary key, second integer);
CREATE OR REPLACE FUNCTION nf() RETURNS TRIGGER AS $$
BEGIN
PERFORM pg_notify('notifytest', format('INSERT %s %s', NEW.first, NEW.second));
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER any_after AFTER INSERT OR UPDATE OR DELETE ON helper FOR EACH ROW EXECUTE PROCEDURE nf();
插入到helper表中,值为('first', 10), ('second', 20);
在C#项目中,我得到以下输出:
事件已处理:INSERT first 10
没有"事件已处理:INSERT second 20"。只有在进行下一操作,如"从helper表中删除"时才会收到它。
为什么?