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

Abi*_*iel 15 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()
Run Code Online (Sandbox Code Playgroud)

最终打印常量记录计数的程序示例(而不是打印最新的记录计数).我只能通过杀死和重新运行脚本或每次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)
Run Code Online (Sandbox Code Playgroud)

Nil*_*esh 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)
Run Code Online (Sandbox Code Playgroud)

光标的定义是它将存储数据直到其更改.所以,你必须通过给予指示光标begin荷兰国际集团或commit荷兰国际集团的连接.这将通知游标您必须从数据库中读取新数据.

希望这会解决您的疑问.

我们也从你的问题中学习新东西:).

  • `DeprecationWarning:begin()是非标准的,将在1.3`中删除 (2认同)
  • 注释`conn.begin()`并取消注释`conn.commit()`.那也行. (2认同)

far*_*awa 5

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

import mysql.connector

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