一、首先下载安装Connector/Python
官网下载地址:https://dev.mysql.com/downloads/connector/python/
安装教程参考官方文档:https://dev.mysql.com/doc/connector-python/en/connector-python-installation.html
二、使用 cursor()方法
创建的游标来查询数据
1 import datetime 2 import mysql.connector 3 4 cnx = mysql.connector.connect(user='scott', database='employees') 5 cursor = cnx.cursor() 6 7 query = ("SELECT first_name, last_name, hire_date FROM employees " 8 "WHERE hire_date BETWEEN %s AND %s") 9 10 hire_start = datetime.date(1999, 1, 1) 11 hire_end = datetime.date(1999, 12, 31) 12 13 cursor.execute(query, (hire_start, hire_end)) 14 15 for (first_name, last_name, hire_date) in cursor: 16 print("{}, {} was hired on {:%d %b %Y}".format( 17 last_name, first_name, hire_date)) 18 19 cursor.close() 20 cnx.close()
三、输出结果
1 Wilharm, LiMin was hired on 16 Dec 1999 2 Wielonsky, Lalit was hired on 16 Dec 1999 3 Kamble, Dannz was hired on 18 Dec 1999 4 DuBourdieux, Zhongwei was hired on 19 Dec 1999 5 Fujisawa, Rosita was hired on 20 Dec 1999