MySQL Connector / Python允許Python程式使用符合Python資料庫API規範v2.0(PEP 249)的API通路MySQL資料庫 。
MySQL Connector / Python包括對以下内容的支援:
幾乎所有MySQL Server提供的功能都包括MySQL Server版本5.7。
Connector / Python 8.0也支援X DevAPI。有關使用X DevAPI的MySQL Connector / Python的概念和用法的文檔,請參閱 X DevAPI使用者指南。
在Python和MySQL資料類型之間來回轉換參數值,例如Python datetime 和MySQL DATETIME。為友善起見,您可以打開自動轉換,或者關閉以獲得最佳性能。
标準SQL文法的所有MySQL擴充。
協定壓縮,可以壓縮用戶端和伺服器之間的資料流。
使用TCP / IP套接字的連接配接和使用Unix套接字的Unix連接配接。
使用SSL保護TCP / IP連接配接。
獨立的驅動。Connector / Python不需要MySQL用戶端庫或标準庫之外的任何Python子產品。
1使用Connector / Python連接配接MySQL
該connect()構造函數建立到MySQL伺服器的連接配接并傳回一個 MySQLConnection對象。
以下示例顯示如何連接配接到MySQL伺服器:
import mysql.connector
cnx = mysql.connector.connect(user='scott', password='password',
host='127.0.0.1',
database='employees')
cnx.close()
也可以使用connection.MySQLConnection() 類建立連接配接對象 :
from mysql.connector import (connection)
cnx = connection.MySQLConnection(user='scott', password='password',
host='127.0.0.1',
database='employees')
cnx.close()
兩種形式(使用connect() 構造函數或直接使用類)都是有效且功能相同的,但是connect()本手冊中的大多數示例都是首選使用的。
要處理連接配接錯誤,請使用該try 語句并使用errors.Error 異常捕獲所有錯誤 :
import mysql.connector
from mysql.connector import errorcode
try:
cnx = mysql.connector.connect(user='scott',
database='employ')
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
else:
cnx.close()
在字典中定義連接配接參數并使用 **運算符是另一種選擇:
import mysql.connector
config = {
'user': 'scott',
'password': 'password',
'host': '127.0.0.1',
'database': 'employees',
'raise_on_warnings': True
}
cnx = mysql.connector.connect(**config)
cnx.close()
2使用Connector / Python建立表
所有DDL(資料定義語言)語句都使用稱為遊标的句柄結構執行。以下示例顯示如何建立Employee示例資料庫的表 。你需要它們用于其他例子。
在MySQL伺服器中,表是非常長壽的對象,并且通常由以不同語言編寫的多個應用程式通路。您通常可以使用已設定的表,而不是在自己的應用程式中建立它們。避免一遍又一遍地設定和丢棄表,因為這是一項昂貴的操作。臨時表是一個例外 ,可以在應用程式中快速建立和删除。
from __future__ import print_function
import mysql.connector
from mysql.connector import errorcode
DB_NAME = 'employees'
TABLES = {}
TABLES['employees'] = (
"CREATE TABLE `employees` ("
" `emp_no` int(11) NOT NULL AUTO_INCREMENT,"
" `birth_date` date NOT NULL,"
" `first_name` varchar(14) NOT NULL,"
" `last_name` varchar(16) NOT NULL,"
" `gender` enum('M','F') NOT NULL,"
" `hire_date` date NOT NULL,"
" PRIMARY KEY (`emp_no`)"
") ENGINE=InnoDB")
TABLES['departments'] = (
"CREATE TABLE `departments` ("
" `dept_no` char(4) NOT NULL,"
" `dept_name` varchar(40) NOT NULL,"
" PRIMARY KEY (`dept_no`), UNIQUE KEY `dept_name` (`dept_name`)"
") ENGINE=InnoDB")
TABLES['salaries'] = (
"CREATE TABLE `salaries` ("
" `emp_no` int(11) NOT NULL,"
" `salary` int(11) NOT NULL,"
" `from_date` date NOT NULL,"
" `to_date` date NOT NULL,"
" PRIMARY KEY (`emp_no`,`from_date`), KEY `emp_no` (`emp_no`),"
" CONSTRAINT `salaries_ibfk_1` FOREIGN KEY (`emp_no`) "
" REFERENCES `employees` (`emp_no`) ON DELETE CASCADE"
") ENGINE=InnoDB")
TABLES['dept_emp'] = (
"CREATE TABLE `dept_emp` ("
" `emp_no` int(11) NOT NULL,"
" `dept_no` char(4) NOT NULL,"
" `from_date` date NOT NULL,"
" `to_date` date NOT NULL,"
" PRIMARY KEY (`emp_no`,`dept_no`), KEY `emp_no` (`emp_no`),"
" KEY `dept_no` (`dept_no`),"
" CONSTRAINT `dept_emp_ibfk_1` FOREIGN KEY (`emp_no`) "
" REFERENCES `employees` (`emp_no`) ON DELETE CASCADE,"
" CONSTRAINT `dept_emp_ibfk_2` FOREIGN KEY (`dept_no`) "
" REFERENCES `departments` (`dept_no`) ON DELETE CASCADE"
") ENGINE=InnoDB")
TABLES['dept_manager'] = (
" CREATE TABLE `dept_manager` ("
" `dept_no` char(4) NOT NULL,"
" `emp_no` int(11) NOT NULL,"
" `from_date` date NOT NULL,"
" `to_date` date NOT NULL,"
" PRIMARY KEY (`emp_no`,`dept_no`),"
" KEY `emp_no` (`emp_no`),"
" KEY `dept_no` (`dept_no`),"
" CONSTRAINT `dept_manager_ibfk_1` FOREIGN KEY (`emp_no`) "
" REFERENCES `employees` (`emp_no`) ON DELETE CASCADE,"
" CONSTRAINT `dept_manager_ibfk_2` FOREIGN KEY (`dept_no`) "
" REFERENCES `departments` (`dept_no`) ON DELETE CASCADE"
") ENGINE=InnoDB")
TABLES['titles'] = (
"CREATE TABLE `titles` ("
" `emp_no` int(11) NOT NULL,"
" `title` varchar(50) NOT NULL,"
" `from_date` date NOT NULL,"
" `to_date` date DEFAULT NULL,"
" PRIMARY KEY (`emp_no`,`title`,`from_date`), KEY `emp_no` (`emp_no`),"
" CONSTRAINT `titles_ibfk_1` FOREIGN KEY (`emp_no`)"
" REFERENCES `employees` (`emp_no`) ON DELETE CASCADE"
") ENGINE=InnoDB")
上面的代碼顯示了我們如何将CREATE語句存儲在 名為的Python字典中 TABLES。我們還在一個名為的全局變量中定義資料庫DB_NAME,這使您可以輕松使用不同的模式。
cnx = mysql.connector.connect(user='scott')
cursor = cnx.cursor()
單個MySQL伺服器可以管理多個 資料庫。通常,您指定要在連接配接到MySQL伺服器時切換到的資料庫。此示例在連接配接時不連接配接到資料庫,是以它可以確定資料庫存在,如果不存在則建立它:
def create_database(cursor):
try:
cursor.execute(
"CREATE DATABASE {} DEFAULT CHARACTER SET 'utf8'".format(DB_NAME))
except mysql.connector.Error as err:
print("Failed creating database: {}".format(err))
exit(1)
try:
cursor.execute("USE {}".format(DB_NAME))
except mysql.connector.Error as err:
print("Database {} does not exists.".format(DB_NAME))
if err.errno == errorcode.ER_BAD_DB_ERROR:
create_database(cursor)
print("Database {} created successfully.".format(DB_NAME))
cnx.database = DB_NAME
else:
print(err)
exit(1)
我們首先嘗試使用database連接配接對象的屬性 更改為特定資料庫 cnx。如果有錯誤,我們檢查錯誤号以檢查資料庫是否不存在。如果是這樣,我們調用 create_database函數為我們建立它。
在任何其他錯誤上,應用程式退出并顯示錯誤消息。
在我們成功建立或更改目标資料庫之後,我們通過疊代TABLES字典的項來建立表 :
for table_name in TABLES:
table_description = TABLES[table_name]
try:
print("Creating table {}: ".format(table_name), end='')
cursor.execute(table_description)
except mysql.connector.Error as err:
if err.errno == errorcode.ER_TABLE_EXISTS_ERROR:
print("already exists.")
else:
print(err.msg)
else:
print("OK")
cursor.close()
cnx.close()
要在表已存在時處理錯誤,我們會通知使用者它已經存在。列印其他錯誤,但我們繼續建立表。(該示例顯示了如何處理 “ 表已存在 ”條件以用于說明目的。在實際應用程式中,我們通常通過使用語句的IF NOT EXISTS子句完全避免錯誤條件CREATE TABLE。)
輸出将是這樣的:
Database employees does not exists.
Database employees created successfully.
Creating table employees: OK
Creating table departments: already exists.
Creating table salaries: already exists.
Creating table dept_emp: OK
Creating table dept_manager: OK
Creating table titles: OK
要填充employees表,請使用Employee Sample Database的轉儲檔案 。請注意,您隻需要在名為的存檔中找到的資料轉儲檔案 employees_db-dump-files-1.0.5.tar.bz2。下載下傳轉儲檔案後,執行以下指令,必要時向mysql指令添加連接配接選項:
shell> tar xzf employees_db-dump-files-1.0.5.tar.bz2
shell> cd employees_db
shell> mysql employees < load_employees.dump
shell> mysql employees < load_titles.dump
shell> mysql employees < load_departments.dump
shell> mysql employees < load_salaries.dump
shell> mysql employees < load_dept_emp.dump
shell> mysql employees < load_dept_manager.dump
3使用Connector / Python插入資料
使用稱為遊标的處理程式結構也可以完成插入或更新資料。當您使用事務性存儲引擎,如InnoDB(在MySQL 5.5和更高的預設設定),則必須送出 的序列後的資料 INSERT, DELETE以及 UPDATE報表。
此示例顯示如何插入新資料。第二個 INSERT取決于第一個新建立的主鍵的值 。該示例還示範了如何使用擴充格式。任務是添加一名新員工,明天開始工作,薪水設定為50000。
注意
以下示例使用示例 “使用Connector / Python建立表”中建立的表。表AUTO_INCREMENT的主鍵的 列選項對于employees確定可靠,易于搜尋的資料非常重要。
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。然後 ,我們使用連接配接的 方法建立一個新的遊标,預設情況下是一個 MySQLCursor對象 cursor()。
4使用Connector / Python查詢資料
以下示例說明如何使用使用連接配接 方法建立的遊标來 查詢資料 cursor()。傳回的資料被格式化并列印在控制台上。
任務是選擇1999年雇用的所有員工,并将他們的姓名和雇用日期列印到控制台。
import datetime
import mysql.connector
cnx = mysql.connector.connect(user='scott', database='employees')
cursor = cnx.cursor()
query = ("SELECT first_name, last_name, hire_date FROM employees "
"WHERE hire_date BETWEEN %s AND %s")
hire_start = datetime.date(1999, 1, 1)
hire_end = datetime.date(1999, 12, 31)
cursor.execute(query, (hire_start, hire_end))
for (first_name, last_name, hire_date) in cursor:
print("{}, {} was hired on {:%d %b %Y}".format(
last_name, first_name, hire_date))
cursor.close()
cnx.close()
我們首先打開與MySQL伺服器的連接配接,并将連接配接對象存儲 在變量中cnx。然後 ,我們使用連接配接的 方法建立一個新的遊标,預設情況下是一個 MySQLCursor對象 cursor()。
5以下示例腳本明天向所有加入2000年且仍在公司的員工送出了15%的提前生效。
為了周遊標明的員工,我們使用緩沖遊标。(緩沖的遊标在執行查詢後擷取并緩沖結果集的行;請參見 第10.6.1節“cursor.MySQLCursorBuffered類”。)這樣,就不必擷取新變量中的行。相反,遊标可以用作疊代器。
from __future__ import print_function
from decimal import Decimal
from datetime import datetime, date, timedelta
import mysql.connector
# Connect with the MySQL Server
cnx = mysql.connector.connect(user='scott', database='employees')
# Get two buffered cursors
curA = cnx.cursor(buffered=True)
curB = cnx.cursor(buffered=True)
# Query to get employees who joined in a period defined by two dates
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, 31)))
# 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))
# Commit the changes
cnx.commit()
cnx.close()
轉載于:https://www.cnblogs.com/XZY30/p/10666063.html