Python 和 MySQL - 更新记录示例
Python 使用 c.execute(q) 函数更新表中的记录,其中 c 是游标,q 是要执行的更新查询。
语法
# 使用 execute() 方法执行 SQL 查询。 cursor.execute(sql) cursor.commit() # 获取更新的记录数 print(mycursor.rowcount, "record(s) impacted")
Sr.No. | 参数及说明 |
---|---|
1 | $sql 必需 - SQL 查询以更新表中的记录。 |
示例
尝试以下示例来更新表中的记录 −
复制并粘贴以下示例为 mysql_example.ty −
#!/usr/bin/python
import MySQLdb
# 打开数据库连接
db = MySQLdb.connect("localhost","root","root@123", "TUTORIALS")
# 使用 cursor() 方法准备游标对象
cursor = db.cursor()
sql = "UPDATE tutorials_tbl set tutorial_title = "Learning Java" where tutorial_id = 2"
# 使用 execute() 方法执行 SQL 查询。
cursor.execute(sql)
db.commit()
# 获取更新的记录数
print(cursor.rowcount, " record(s) impacted")
# 断开与服务器的连接
db.close()
输出
使用 python 执行 mysql_example.py 脚本并验证输出。
1 record(s) affected