MySQL Connector/Python 2.0是目前正在开发的版本,MySQL Connector/Python 1.0, 1.1, 和1.2已经不再开发。下表是对应版本与支持的MySQL的版本:
Connector/Python 版本 | MySQL服务器版本 | Python版本 | Support Status for Connector |
2.0 | 5.7, 5.6, 5.5 | 3.3 或以后版本, 2.7, 2.6 | Recommended version |
1.1, 1.2 | 5.7, 5.6, 5.5 (5.1, 5.0, 4.1) | 3.1 或以后版本, 2.7, 2.6 | Recommended version |
1.0 | 5.7, 5.6, 5.5 (5.1, 5.0, 4.1) | 3.1 或以后版本, 2.7, 2.6 (2.5, 2.4) | Recommended version |
5.1 使用连接器连接MySQL服务器
5.2 使用连接器创建数据表
5.3 使用连接器插入数据
5.4 使用连接器查询数据
这些代码例子演示怎么样通过Python连接器来连接MySQL服务器。
使用connect()函数来创建一个连接到MySQL服务器,成功之后返回MySQLConnection对象。下面的例子演示怎么样连接到MySQL服务器:
import mysql.connector cnx = mysql.connector.connect(user='root', password='123456', host='127.0.0.1', database='mysql') cnx.close()
这里使用到的参数,后面再详细描述,通过这样的方式就可以创建一个连接到数据库的连接。
也可以采用connect.MySQLConnection()类的方式来创建连接:
from mysql.connector import (connection) cnx = connection.MySQLConnection(user='root', password='123456', host='127.0.0.1', database='mysql') cnx.close()
使用这两种方法创建连接是等效的,不过在本文里使用connector()函数方式会更多一些。
由于连接服务器会出各种各样的错误,所以要使用try...catch语句来捕捉异常,异常抛出错误在errors.Error里:
import mysql.connector from mysql.connector import errorcode try: cnx = mysql.connector.connect(user='scott', database='testt') 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()
在这个例子里,如果在连接时发生异常,就会查找异常错误,判断在那一种错误,就输出相应的字符串。如果没有发生异常,就直接运行到else语句那里,直接关闭数据库连接。
如果有很多连接参数,最好的解决方案是采用字典方式,以及采用**操作符自动分解参数:
import mysql.connector config = { 'user': 'root', 'password': '123456', 'host': '127.0.0.1', 'database': 'cai', 'raise_on_warnings': True, } cnx = mysql.connector.connect(**config) cnx.close()
在新版本的连接器里,可以根据连接输入的参数use_pure来决定是否采用纯python方式,还是采用C扩展方式。默认的情况下,这个参数是设置为True,也即是采用纯python的方式。如果在安装时,也包括了C扩展库,就可以设置这个参数为False方式来选择这种方式工作。
import mysql.connector cnx = mysql.connector.connect(user='root', password='123456', host='127.0.0.1', database='cai', use_pure=False) cnx.close()
或者采用字典参数的方式:
import mysql.connector config = { 'user': 'root', 'password': '123456', 'host': '127.0.0.1', 'database': 'cai', 'raise_on_warnings': True, 'use_pure': False, } cnx = mysql.connector.connect(**config) cnx.close()
当使用C扩展的方式时,它是导入_mysql_connector模块来代替mysql.connector模块。
创建数据库的例子:
#python 3.4 #蔡军生 2016-6-16 # from __future__ import print_function import mysql.connector from mysql.connector import errorcode #数据库名称 DB_NAME = 'employees' #连接数据库 cnx = mysql.connector.connect(user='root', password='123456') cursor = cnx.cursor() #创建数据库函数 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: cnx.database = DB_NAME except mysql.connector.Error as err: if err.errno == errorcode.ER_BAD_DB_ERROR: create_database(cursor) cnx.database = DB_NAME else: print(err) exit(1) cursor.close() cnx.close()
在这个例子里,使用CREATE DATABASE {} DEFAULT CHARACTER SET 'utf8来创建数据库employees,注意在这里也使用{}来格式化字符串参数,而不是使用拼接的方式。
下面的例子来创建数据库表:
#python 3.4 #蔡军生 2016-6-16 # 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") #连接数据库 cnx = mysql.connector.connect(user='root', password='123456') cursor = cnx.cursor() #创建数据库函数 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: cnx.database = DB_NAME except mysql.connector.Error as err: if err.errno == errorcode.ER_BAD_DB_ERROR: create_database(cursor) cnx.database = DB_NAME else: print(err) exit(1) #创建数据表 for name, ddl in TABLES.items(): try: print("Creating table {}: ".format(name), end='') cursor.execute(ddl) 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()
在这个例子里使用字典来保存要创建的数据表定义语句,如果有N个表创建,就可以保存N项表,表名称是字典的key,表定义语句是字典的键值。判断一个表是否存在,也可以采用MYSQL语句来实现,比如使用IF NOT EXISTS放在创建表的前面。
插入数据也是使用光标对象来操作,对于有事务性操作的InnoDB表,需要使用提交事务完成才可以真正完成数据插入。例子如下:
#python 3.4 #蔡军生 2016-6-16 # from __future__ import print_function from datetime import date, datetime, timedelta import mysql.connector #创建连接 cnx = mysql.connector.connect(user='root', password='123456', 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)") data_employee = ('Geert', 'Vanderkelen', tomorrow, 'M', date(1977, 6, 14)) # 插入一个新顾员 cursor.execute(add_employee, data_employee) # 提交事务完成 cnx.commit() cursor.close() cnx.close()
下面的例子采用光标对象来演示查询数据出来:
#python 3.4 #蔡军生 2016-6-16 # import datetime import mysql.connector #创建数据库连接 cnx = mysql.connector.connect(user='root', password='123456', 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(2026, 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()
到这里,已经把数据库创建、数据库表创建、数据插入和数据查询已经学习完成。
蔡军生 QQ:9073204 深圳