Python 操作 MySQL 数据库
1.安装驱动
pip install mysql-connector-python
2.查询及错误处理
import mysql.connector from mysql.connector import errorcode # cnx = mysql.connector.connect(user='scott', password='password', # host='127.0.0.1', # database='employees') # cnx.close() try: cnx = mysql.connector.connect(user='root', password='', host='127.0.0.1', database='bugfree') cursor = cnx.cursor() query = "select * from bf_bug_info" cursor.execute(query) #单条取值方式 while (True): data = cursor.fetchone() if data == None: break print(data) #全部取值方式 # datas = cursor.fetchall() # for data in datas: # print(data) # print(datas) 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) finally : cursor.close() cnx.close() #官方示例 # 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()