python: how to get notifications for mysql database changes?

后端 未结 5 1299
猫巷女王i
猫巷女王i 2020-11-30 10:43

In Python, is there a way to get notified that a specific table in a MySQL database has changed?

5条回答
  •  抹茶落季
    2020-11-30 11:25

    If by changed you mean if a row has been updated, deleted or inserted then there is a workaround.

    You can create a trigger in MySQL

    DELIMITER $$
    
    CREATE TRIGGER ai_tablename_each AFTER INSERT ON tablename FOR EACH ROW
    BEGIN
      DECLARE exec_result integer;
    
      SET exec_result = sys_exec(CONCAT('my_cmd '
                                        ,'insert on table tablename '
                                        ,',id=',new.id));
      IF exec_result = 0 THEN BEGIN
        INSERT INTO table_external_result (id, tablename, result) 
          VALUES (null, 'tablename', 0)
      END; END IF;
    END$$
    
    DELIMITER ;
    

    This will call executable script my_cmd on the server. (see sys_exec fro more info) with some parameters.

    my_cmd can be a Python program or anything you can execute from the commandline using the user account that MySQL uses.

    You'd have to create a trigger for every change (INSERT/UPDATE/DELETE) that you'd want your program to be notified of, and for each table.
    Also you'd need to find some way of linking your running Python program to the command-line util that you call via sys_exec().

    Not recommended
    This sort of behaviour is not recommend because it is likely to:

    1. slow MySQL down;
    2. make it hang/timeout if my_cmd does not return;
    3. if you are using transaction, you will be notified before the transaction ends;
    4. I'm not sure if you'll get notified of a delete if the transaction rolls back;
    5. It's an ugly design

    Links
    sys_exec: http://www.mysqludf.org/lib_mysqludf_sys/index.php

提交回复
热议问题