即使在提交更改后,MySQL-python连接也看不到对另一个连接上的数据库所做的更改

时间:2012-02-16 04:44:20

标签: python mysql cursor mysql-python

我使用MySQL的MySQLdb模块(用于Windows Python 2.7的v1.2.3预编译二进制文件)来读取和写入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 个答案:

答案 0 :(得分:12)

试试这个

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的定义是它将存储数据直到其更改。所以你必须通过begincommit你的连接给光标指示。这将通知游标您必须从数据库中读取新数据。

希望这会解决您的问题。

我们也从您的问题中学习新事物:)。

答案 1 :(得分:1)

这是一个古老的问题,但是如果有人遇到相同的问题,则需要在连接声明中启用自动提交:

import mysql.connector

conn = mysql.connector.connect(
  host='localhost',
  port='3306',
  user='root',
  passwd='rootpassword',
  auth_plugin='mysql_native_password',
  autocommit=True
)