本文參見這裏。html
使用緩衝的 cursor,下例給從2000年加入公司而且還在公司的員工薪水從明天起加15%python
from __future__ import print_function from decimal import Decimal from datetime import datetime, date, timedelta import mysql.connector tomorrow = datetime.now().date() + timedelta(days=1) print("明天日期是: {}".format(tomorrow)) # 鏈接到服務器 cnx = mysql.connector.connect(user='lintex9527', password='lintex9527',database='employees') # 得到兩個緩衝的cursor curA = cnx.cursor(buffered=True) curB = cnx.cursor(buffered=True) # 查詢在指定日期加入公司的員工 query = ( "SELECT s.emp_no, salary, from_date, to_date FROM employees AS e " "LEFT JOIN salaries AS s USING (emp_no) " "WHERE to_date=DATE('9999-01-01') " "AND e.hire_date BETWEEN DATE(%s) AND DATE(%s)") # UPDATE and INSERT statements for the old and new salary update_old_salary = ( "UPDATE salaries SET to_date = %s " "WHERE emp_no=%s AND from_date=%s") insert_new_salary = ( "INSERT INTO salaries (emp_no, from_date, to_date, salary) " "VALUES (%s, %s, %s, %s)") # Select the employees getting a raise curA.execute(query, (date(2000, 1, 1), date(2000, 12, 30))) # Iterate through the result of curA for (emp_no, salary, from_date, to_date) in curA: # update the old and insert the new salary new_salary = int(round(salary * Decimal('1.15'))) curB.execute(update_old_salary, (tomorrow, emp_no, from_date)) curB.execute(insert_new_salary, (emp_no, tomorrow, date(9999, 1,1,), new_salary)) # 提交操做 cnx.commit() print("操做完成,關閉連接") cnx.close()