Python mysql connector query same result every time

44
January 13, 2019, at 07:20 AM

I want to access a mysql database via mysql.connector in python 2.7.

The Problem is, that the query result does not update.

#!/usr/bin/python
import mysql.connector
from time import sleep

if __name__ == "__main__":
    cnx = mysql.connector.connect(user="test", password="password", database="test")
    query = "select * from message"
    while True:
        cursor = cnx.cursor()
        cursor.execute(query)
        print(cursor.fetchall())
        cursor.close()
        sleep(1)

When I insert a row in the table message the print output does not change. But when I restart the program it will print the current state of the database.

The table message is only a table with 1 column message varchar(255).

Thanks for your time.

Update:

It works if you reinitialize the db connection every time:

...
if __name__ == "__main__":
    query = "select * from message"
    while True:
        cnx = mysql.connector.connect(user="test", password="password", database="test")
        cursor = cnx.cursor()
...
Answer 1

i solve your problem but i used the module pymysql instead of mysql.connector.

#!/usr/bin/python
import pymysql
from time import sleep
if __name__=="__main__":
    query="select * from message"
    while True:
       try:
         cnx=pymysql.connect('localhost','test','password','test')
#                              server     user    password  database
       except:
         exit()
       cursor=cnx.cursor()
       cursor.execute(query)
       print(cursor.fetchall())
       cursor.close()
       cnx.close()
       sleep(1)
READ ALSO
Is there a way to fetch string value from MySQL database through Karate

Is there a way to fetch string value from MySQL database through Karate

I am having an issue while karate fetches a string value from MySQL dbreadValue works fine if it is string value it fetches from db but getting error like Unknown column 'SMEMSD22' in 'where clause' How to deal with alphanumeric data with karate

36
Column count doesn't match value count at row 1 in MySQL

Column count doesn't match value count at row 1 in MySQL

I have created a table with the following query:

24
How to mirror mysql database traffic to another server

How to mirror mysql database traffic to another server

I have two server Mysql database in Cent OS 7Server A(192

27