Python 及 MySQL - 更新記錄示例



Python 使用 c.execute(q) 函式更新資料表中的記錄,其中 c 是遊標,q 是要執行的更新查詢。

語法

# execute SQL query using execute() method.
cursor.execute(sql)

cursor.commit()

# get the record count updated
print(mycursor.rowcount, "record(s) affected")

序號 引數及說明
1

$sql

必需 - 用於更新資料表中的記錄的 SQL 查詢。

示例

嘗試以下示例來更新資料表中的記錄 -

將以下示例複製貼上為 mysql_example.ty -

#!/usr/bin/python

import MySQLdb

# Open database connection
db = MySQLdb.connect("localhost","root","root@123", "TUTORIALS")

# prepare a cursor object using cursor() method
cursor = db.cursor()

sql = "UPDATE tutorials_tbl set tutorial_title = "Learning Java" where tutorial_id = 2"

# execute SQL query using execute() method.
cursor.execute(sql)

db.commit()

# get the record count updated
print(cursor.rowcount, " record(s) affected")

# disconnect from server
db.close()

輸出

使用 python 執行 mysql_example.py 指令碼,並驗證輸出。

1 record(s) affected
廣告
© . All rights reserved.