geekdoc-python-zh/docs/overiq/237.md

1.2 KiB

使用 Connector/Python 更新数据

原文:https://overiq.com/mysql-connector-python-101/updating-data-using-connector-python/

最后更新于 2020 年 7 月 27 日


在上一课中,我们看到了如何在表中插入行。在本课中,我们将看到如何更新数据的示例。

更新单行

import mysql.connector

db = mysql.connector.connect(option_files='my.conf', use_pure=True)

cursor = db.cursor(buffered=True)

sql1 = "update category set name=%s WHERE ID=2"

data1 = ('CSS',)

cursor.execute(sql1, data1)

db.commit()  # commit the changes

print("Rows affected:", cursor.rowcount)

cursor.close()
db.close()

预期输出:

Rows affected: 1

批量更新行

import mysql.connector
from datetime import datetime, timedelta

db = mysql.connector.connect(option_files='my.conf', use_pure=True)

cursor = db.cursor(buffered=True)

sql1 = "update post set date=%s"

data1 = [
            (datetime.now().date() + timedelta(days=10),), 
        ]

cursor.executemany(sql1, data1)

db.commit()  # commit the changes

print("Rows affected:", cursor.rowcount)

cursor.close()
db.close()

预期输出:

Rows affected: 6