我正在使用适用于Python的MySQLdb模块(适用于Windows Python 2.7的v1.2.3预编译二进制文件)来将数据读取和写入MySQL数据库。打开一个连接后,我可以使用该连接来观察对该连接上的数据库所做的更改,但是无论该其他连接是使用Python还是使用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)
尝试一下
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)
cursor的定义是它将存储数据直到其更改。因此,您必须通过begin
或commit
连接来给光标指示。这将通知游标您必须从数据库读取新数据。
希望这会解决您的查询。
我们还从您的问题中学习新事物:)。
这是一个古老的问题,但是如果有人遇到相同的问题,您需要在连接声明中启用自动提交:
import mysql.connector
conn = mysql.connector.connect(
host='localhost',
port='3306',
user='root',
passwd='rootpassword',
auth_plugin='mysql_native_password',
autocommit=True
)