Python MySQL – Update Data in a Table

摘要:本教程将引导您完成使用 MySQL Connector/Python API 更新 MySQL 表中的数据所需的步骤。

要在 Python 中更新 MySQL 表中的数据,请执行以下步骤:

  1. 通过创建新的MySQLConnection对象连接到数据库
  2. MySQLConnection对象创建一个新的MySQLCursor对象,并调用MySQLCursor对象的execute()方法。要接受更改,请在调用execute()方法后调用MySQLConnection对象的commit()方法。否则,不会对数据库进行任何更改。
  3. 关闭游标和数据库连接。

以下示例更新由图书 id 指定的图书的标题:

from mysql.connector import MySQLConnection, Error
from python_mysql_dbconfig import read_db_config


def update_book(book_id, title):
    # read database configuration
    db_config = read_db_config()

    # prepare query and data
    query = """ UPDATE books
                SET title = %s
                WHERE id = %s """

    data = (title, book_id)

    try:
        conn = MySQLConnection(**db_config)

        # update book title
        cursor = conn.cursor()
        cursor.execute(query, data)

        # accept the changes
        conn.commit()

    except Error as error:
        print(error)

    finally:
        cursor.close()
        conn.close()


if __name__ == '__main__':
    update_book(37, 'The Giant on the Hill *** TEST ***')Code language: Python (python)

在此模块中,我们使用了在 Python 连接数据库教程中创建的python_mysql_dbconfig模块中的read_db_config()函数。

我们在UPDATE 语句中放置了两个占位符 (%),一个用于书名,另一个用于书 ID。我们将UPDATE语句( query )和(title,id)元组传递给了execute()方法。连接器会将查询解释为以下内容:

UPDATE books
SET title = 'The Giant on the Hill *** TEST ***'
WHERE id = 37Code language: SQL (Structured Query Language) (sql)

重要的是要理解,我们应该始终在包含用户输入的任何 SQL 语句中使用占位符 ( %s )。这有助于我们防止 SQL 注入。

让我们测试我们的新模块,看看它是否有效。

首先选择id为37的书:

SELECT * FROM books
WHERE id = 37;Code language: SQL (Structured Query Language) (sql)
+----+------------------------+---------------+
| id | title                  | isbn          |
+----+------------------------+---------------+
| 37 | The Giant on the Hill  | 1235644620578 |
+----+------------------------+---------------+
1 row in set (0.00 sec)Code language: JavaScript (javascript)

其次,执行update.py模块。

python update.pyCode language: SQL (Structured Query Language) (sql)

第三,通过执行SELECT语句来选择书籍以验证更改:

+----+------------------------------------+---------------+
| id | title                              | isbn          |
+----+------------------------------------+---------------+
| 37 | The Giant on the Hill *** TEST *** | 1235644620578 |
+----+------------------------------------+---------------+
1 row in set (0.00 sec)Code language: JavaScript (javascript)

它按预期工作。

在本教程中,您学习了如何使用 MySQL Connector/Python API 更新表中的数据。

本教程有帮助吗?