MySQL-python连接无法看到另一个连接提交的数据库更改
我正在使用MySQLdb模块来处理Python(版本1.2.3,适用于Windows的Python 2.7),用来读写MySQL数据库中的数据。一旦连接打开,我可以通过这个连接看到在数据库上做的更改,但如果是通过其他连接进行的更改,无论是用Python还是用MySQL命令行客户端,我都看不到这些更改。特别是当我用Python进行更新时,我已经在连接上运行了commit()命令。
下面是一个示例程序,它向一个测试表中插入新记录,这个表里有一个VARCHAR类型的列:
import MySQLdb
conn = MySQLdb.connect("localhost", "test", "test", "test")
c = conn.cursor()
c.execute("INSERT INTO test VALUES(%s)", ("Test",))
conn.commit()
c.close()
conn.close()
下面是一个示例程序,它的输出总是显示一个固定的记录数(而不是最新的记录数)。我只能通过结束并重新运行脚本,或者每次运行SELECT
语句时打开一个新连接来更新这个记录数。
import MySQLdb
conn = MySQLdb.connect("localhost", "test", "test", "test")
while True:
input = raw_input("Enter anything: ")
if input == "exit":
break
c = conn.cursor()
c.execute("SELECT COUNT(*) FROM test")
res = c.fetchone()[0]
c.close()
print("Number of records: %d" % res)
2 个回答
5
这是一个老问题,但如果有人遇到同样的情况,你需要在连接声明中启用自动提交:
import mysql.connector
conn = mysql.connector.connect(
host='localhost',
port='3306',
user='root',
passwd='rootpassword',
auth_plugin='mysql_native_password',
autocommit=True
)
13
试试这个
import MySQLdb
import time
from MySQLdb.cursors import SSCursor
conn = MySQLdb.connect("localhost", "test", "test", "test")
while True:
input = raw_input("Enter anything: ")
if input == "exit":
break
c = conn.cursor()
conn.begin()
c.execute("SELECT COUNT(*) FROM test")
res = c.fetchone()[0]
#c.commit()
c.close()
print("Number of records: %d" % res)
所谓的游标,就是用来存储数据,直到这些数据发生变化。所以你需要通过begin
或者commit
来告诉游标你的连接状态。这会告诉游标你需要从数据库中读取新的数据。
希望这能解决你的问题。
我们也从你的问题中学到了新东西 :).