需要帮助诊断Python/MySQL插入/更新异常吗

2024-05-14 07:17:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习使用MySQL Connector/Python库访问MySQL数据库mysql.org网站网站。我的环境是OSX10.6、Eclipse Indigo with PyDev和新安装的MySql(5.5.28,64位)、Sequel Pro和phpMyAdmin的新安装版本。在

我的测试数据库有一个表“Employees”,其中有“id”、“name”和“ssn”列。最初,有两行:(1,Lucy,1234)和(2,Alex,3456)。在

这是Python脚本。变量“config”包含数据库的有效访问信息。在

import mysql.connector
from mysql.connector import errorcode

config = {…}

try:
    cnx = mysql.connector.connect(**config)
except mysql.connector.Error as err:
    if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print("Something is wrong your username or password")
    elif err.errno == errorcode.ER_BAD_DB_ERROR:
        print("Database does not exist")
    else:
        print(err)
else:
    print ("original database contents")

    cursor = cnx.cursor()
    query = ("SELECT name, ssn FROM Employees")  # fetches all employees names and ssns
    cursor.execute(query)
    for (name, ssn) in cursor:  # iterates over fetched data
        print(name, ssn)  # print one employee per line
    cursor.close;

    # block 1: insert a new employee into row 3
    cursor = cnx.cursor()
    cursor.execute("INSERT INTO Employees (id, name, ssn) VALUES (3, 'Sam', '5678')")
    cnx.commit()
    cursor.close()

    # block 2: update the name in the first row
    cursor = cnx.cursor()
    cursor.execute("UPDATE Employees SET name='Ethel' WHERE id=1")
    cnx.commit;
    cursor.close()

    print ("after inserting Sam and updating Lucy to Ethel")

    cursor = cnx.cursor()
    query = ("SELECT name, ssn FROM Employees")  # fetches all employees' names and ssns
    cursor.execute(query)
    for (name, ssn) in cursor:  # iterates over fetched data
        print(name, ssn)  # print one employee per line
    cursor.close;

cnx.close()

print ("end of database test")

使用insert在初始数据库上运行Python脚本,然后执行update会得到:

^{pr2}$

使用phpMyAdmin或Sequel Pro查看数据库时,第1行中的名称仍显示为“Lucy”。在

在带有update的初始数据库上运行Python脚本,然后insert(颠倒脚本中块1和块2的顺序)得到:

^{pr2}$

使用phpMyAdmin或Sequel Pro查看数据库时,第1行中的名称显示为“Ethel”。在

从Sequel Pro中打开的初始数据库开始,我可以按任意顺序执行这两个查询并获得正确的结果。在

似乎与提交对数据库的更改相关的东西出了问题,但是作为一个新手,我没有看到它。如果您能帮我诊断这个问题,我将不胜感激。在


Tags: name脚本数据库closeconnectormysqlquerycursor
1条回答
网友
1楼 · 发布于 2024-05-14 07:17:27

您需要调用commit方法将更改提交到数据库,否则事务将永远不会保存,其他连接也看不到更改。在

cnx.commit()

您在代码中省略了()括号。在

您还可以在多个位置引用cursor.close方法,而不调用它;这并不像Python通过垃圾收集自动清理这些方法那样重要。在

相关问题 更多 >

    热门问题