MySQLMySQL Connector/Python 接口 (三)

正文参见这里。

应用缓冲的
cursor,下例给起2000年进入公司同时还以铺的职工薪水由明于加15%

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()
网站地图xml地图