插入或更新資料也是使用稱為游標的處理程式結構來完成。當您使用交易式儲存引擎 (例如 InnoDB
,MySQL 5.5 及更高版本中的預設值) 時,您必須在執行一系列的 INSERT
、DELETE
和 UPDATE
陳述式後,提交 資料。
此範例示範如何插入新資料。第二個 INSERT
取決於第一個 主索引鍵 的新建立值。此範例也示範如何使用擴充格式。任務是新增一名明天開始工作的新員工,薪資設定為 50000。
以下範例使用在 第 5.2 節「使用 Connector/Python 建立資料表」中的範例建立的資料表。 employees
資料表主索引鍵的 AUTO_INCREMENT
資料行選項對於確保可靠、容易搜尋的資料至關重要。
from __future__ import print_function
from datetime import date, datetime, timedelta
import mysql.connector
cnx = mysql.connector.connect(user='scott', database='employees')
cursor = cnx.cursor()
tomorrow = datetime.now().date() + timedelta(days=1)
add_employee = ("INSERT INTO employees "
"(first_name, last_name, hire_date, gender, birth_date) "
"VALUES (%s, %s, %s, %s, %s)")
add_salary = ("INSERT INTO salaries "
"(emp_no, salary, from_date, to_date) "
"VALUES (%(emp_no)s, %(salary)s, %(from_date)s, %(to_date)s)")
data_employee = ('Geert', 'Vanderkelen', tomorrow, 'M', date(1977, 6, 14))
# Insert new employee
cursor.execute(add_employee, data_employee)
emp_no = cursor.lastrowid
# Insert salary information
data_salary = {
'emp_no': emp_no,
'salary': 50000,
'from_date': tomorrow,
'to_date': date(9999, 1, 1),
}
cursor.execute(add_salary, data_salary)
# Make sure data is committed to the database
cnx.commit()
cursor.close()
cnx.close()
我們首先開啟與 MySQL 伺服器的連線,並將 連線物件 儲存在變數 cnx
中。然後,我們使用連線的 cursor()
方法建立新的游標,預設為 MySQLCursor 物件。
我們可以透過呼叫資料庫函式來計算明天,但為了清楚起見,我們在 Python 中使用 datetime
模組來完成。
兩個 INSERT
陳述式都儲存在稱為 add_employee
和 add_salary
的變數中。請注意,第二個 INSERT
陳述式使用擴充的 Python 格式程式碼。
新員工的資訊儲存在元組 data_employee
中。執行插入新員工的查詢,並使用游標物件的 lastrowid
屬性擷取 emp_no
資料行 (一個 AUTO_INCREMENT
資料行) 的新插入值。
接下來,我們使用字典中包含的 emp_no
變數,為新員工插入新薪資。如果發生錯誤,則將此字典傳遞至游標物件的 execute()
方法。
由於 Connector/Python 預設會關閉自動提交,且 MySQL 5.5 及更高版本預設使用交易式 InnoDB
資料表,因此必須使用連線的 commit()
方法來提交變更。您也可以使用 rollback()
方法復原。