【问题标题】:MySQL-python connection does not see changes to database made on another connection even after change is committed即使在提交更改后,MySQL-python 连接也看不到在另一个连接上对数据库所做的更改
【发布时间】:2012-03-07 12:28:40
【问题描述】:

我正在使用 Python 的 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)

【问题讨论】:

    标签: python mysql mysql-python database-cursor


    【解决方案1】:

    试试这个

    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 的定义是它将存储数据直到它发生变化。因此,您必须通过begining 或commiting 您的连接向光标指示。这将通知游标您必须从数据库中读取新数据。

    希望这能解决您的问题。

    我们还从您的问题中学到了新东西:)。

    【讨论】:

    • DeprecationWarning: begin() is non-standard and will be removed in 1.3
    • 评论 conn.begin() 并取消评论 conn.commit()。这也行。
    【解决方案2】:

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

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

    【讨论】:

    • 为我工作。您能否详细说明自动提交如何/为什么连接到 SELECT?我认为自动提交在使用 INSERT/UPDATE 时很重要。我还有一个查找更改的脚本(在我的情况下,我通过工作台而不是另一个脚本更改数据库)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-11
    • 1970-01-01
    • 1970-01-01
    • 2010-11-04
    • 2017-12-26
    • 1970-01-01
    相关资源
    最近更新 更多