Python的Mysql操作

來源:互聯網
上載者:User

標籤:new   and   port   rom   網上   命令   who   ISE   code   

網上好多的文章感覺比較老了,而且千篇一律。我到mysql看了一下官網上python驅動的操作,發現與大部分網站說的都不一樣。

首先安裝的驅動是:

pip install mysql-connector-python

上面是在ubuntu上的命令。

安裝之後,開發的範例代碼如下:

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 two buffered cursorscurA = cnx.cursor(buffered=True)curB = cnx.cursor(buffered=True)# Query to get employees who joined in a period defined by two 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 INSERT statements for the old and new salaryupdate_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 raisecurA.execute(query, (date(2000, 1, 1), date(2000, 12, 31)))# 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 * 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))  # Commit the changes  cnx.commit()cnx.close()

Python的Mysql操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.