While-loop in Python script not working when a record is added in MySQL table from triggers

11 Views Asked by At

I have the following MySQL trigger script

CREATE TRIGGER table_1_insert
AFTER INSERT ON Table1
FOR EACH ROW
BEGIN
    INSERT INTO Logs (time, table_name)
    VALUES (NOW(), 'Table1');
END;

I also have following Python script

def listen_to_triggers():
    try:
        conn = mysql.connector.connect(
            host="localhost",
            port=<port>,
            database=<db_name>,
            user=<user>,
            password=<password>,
        )

        if conn.is_connected():
            print("Connected to MySQL database")

        while True:
            cursor = conn.cursor()

            # Query for new trigger events
            cursor.execute("SELECT * FROM logs)
            rows = cursor.fetchall()

            for row in rows:
 
                print("Time:", row[1])
                print("Table Name:", row[2])

            cursor.close()
            time.sleep(1)

    except Error as e:
        print(e)

    finally:
        if conn.is_connected():
            conn.close()
            print("Connection closed")

if __name__ == "__main__":
    listen_to_triggers()

The issue I am facing is when I run the Python script and insert a record in Table1, the prints do not show up. When I stop the script and re-run it, I get the print of the data. The Python while-loop is still running in the first run though and yet it does not print out.

Your support on this would be greatly appreciated. Thanks.

0

There are 0 best solutions below