Функция запуска Postgres C # - PullRequest
0 голосов
/ 30 июня 2018

Я пытаюсь вызвать функцию, когда новые данные добавляются в базу данных.

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;' В уставе я получаю эту ошибку:

: 'Ключевое слово не поддерживается: синхронизация Имя параметра: ключевое слово '

Что я делаю не так?

Спасибо

Ответы [ 2 ]

0 голосов
/ 13 мая 2019

Пример кода с версией 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");
}
0 голосов
/ 07 июля 2018

Я использовал последнюю версию NPGSQL, 3.6.2 (я думаю), где в качестве другого проекта использовалась версия 2.11.96. Так как с использованием более старой версии программа работает. Я полагаю, что более новый NPGSQL использует другой способ выполнения триггерных функций.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...