简体   繁体   中英

mysql.connector do not give the last database state in Python

I use mysql.connector library in Python to send query to database. But, when the database is changed after the initialization, the mysql.connector 's tools answer like if the database had never change.

As example, let's imagine I have a minimalist table students with just two columns id and name .

+----+------+
| id | name |
+----+------+
| 0  | foo  |
+----+------+

In the following code, the query will ask the user with id 0. But, inside the process, some events will happened from outside the Python script and alter the database.

import mysql.connector

maindb = mysql.connector.connect(
    host = "<host>",
    user = "<user>",
    password = "<password>",
    db = "<database name>"
)

cursor = maindb.cursor()

# Here, I will send outside the python script a MySQL query to modify the name of the student from “foo” to “bar” like this:
# `UPDATE `students` SET `name` = 'bar' WHERE `students`.`id` = 0;`

cursor.execute("SELECT `id`, `name` FROM `students` WHERE `id` = 0")
result = cursor.fetchall()
print(result)

Then I get this answer [(0, 'foo')] . As you see, Python is not aware the data base has change since maindb.cursor() was called. So I get foo as name field instead of bar as expected.

So how to tell mysql.connector 's tools to take the last updates from the database when I send a query?

您将需要使用套接字,或者如果更改频繁发生,则每隔 x 分钟重新运行一次代码

The database maintains data integrity by preventing in-progress transactions from seeing changes made by other transactions (see transaction isolation levels ).

You can commit your connection to allow it to see new changes:


cursor = maindb.cursor()


# Here, I will send outside the python script a MySQL query to modify the name of the student from “foo” to “bar” like this:
# `UPDATE `students` SET `name` = 'bar' WHERE `students`.`id` = 0;`

# Doesn't show the update
cursor.execute("SELECT `id`, `name` FROM `students` WHERE `id` = 0")
result = cursor.fetchall()
print(result)  

# Shows the update because we have committed.
maindb.commit()
cursor.execute("SELECT `id`, `name` FROM `students` WHERE `id` = 0")
result = cursor.fetchall()
print(result)

I just need to .connect() maindb object and .close() it before each new need.

maindb.connect()

cursor.execute("SELECT `id`, `name` FROM `students` WHERE `id` = 0")
result = cursor.fetchall()
print(result)

maindb.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM