The MySQL operation of Python

Source: Internet
Author: User

Online a lot of posts feel older, and stereotyped. I went to MySQL to see the official online python-driven operation, and found that most of the site is not the same.

The drivers that are installed first are:

pip install mysql-connector-python

The above is the command on Ubuntu.

After installation, the sample code developed is as follows:

From __future__ import print_functionfrom decimal Import decimalfrom datetime import datetime, date, Timedeltaimport MySQL . connector# Connect with the MySQL SERVERCNX = Mysql.connector.connect (user= ' Scott ', database= ' employees ') # Get both Buffe  Red Cursorscura = Cnx.cursor (buffered=true) CurB = Cnx.cursor (buffered=true) # Query to get employees who joined in a period  Defined by-datesquery = ("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 in SERT statements for the old and new salaryupdate_old_salary = ("UPDATE salaries SET to_date =%s" "WHERE emp_no =%s A ND 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 raisecura.execute (query, (date (1, 1), date (+, +))) # Iterate through The result of Curafor (EMp_no, salary, From_date, to_date) in CurA: # Update The old and insert the new salary new_salary = Int (Round (Salary * D               Ecimal (' 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)) # Commit the changes cnx.commit () Cnx.close ()

Python's MySQL operation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.