Repeated MySQL queries from Python

后端 未结 2 1287
遥遥无期
遥遥无期 2021-01-25 02:48

I need to repeatedly query a MySQL DB from Python, as the data is rapidly changing. Each time the data is read, it is transferred into a list.

I had assumed that simply

2条回答
  •  清酒与你
    2021-01-25 03:33

    You need to commit the connection after each query. This commits the current transaction and ensures that the next (implicit) transaction will pick up changes made while the previous transaction was active.

    # Main loop
    while True:
    
        # SQL query
        sql = "SELECT * FROM table"
    
        # Read the database, store as a dictionary
        mycursor = mydb.cursor(dictionary=True)
        mycursor.execute(sql)
    
        # Store data in rows
        myresult = mycursor.fetchall()
    
        # Transfer data into list
        for row in myresult:
            myList[int(row["rowID"])] = (row["a"], row["b"], row["c"])
    
            print(myList[int(row["rowID"])])
    
        # Commit !
        mydb.commit()
        print("---")
        sleep (0.1)
    

    The concept here is isolation levels. From the docs (emphasis mine):

    REPEATABLE READ

    This is the default isolation level for InnoDB. Consistent reads within the same transaction read the snapshot established by the first read.

提交回复
热议问题