本文參見這裏,示例如何鏈接MySQL 數據庫。html
import mysql.connector from mysql.connector import errorcode # 鏈接數據庫須要的參數 # `use_pure` 表示使用純Python版本的接口,若是置爲False,表示使用C庫版本的接口,前提是你已經安裝了C庫版本的接口。 config = { 'user':'scott', 'password':'tiger', 'host':'127.0.0.1', 'database':'employees', 'raise_on_warnings':True, 'use_pure':False, } try: cnx = mysql.connector.connect(**config) # do something ... # ... #最後關閉鏈接 cnx.close() 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)
本文參見這裏,全部的DDL語句都是經過 cursor 執行的,下面的例子介紹瞭如何經過 cursor 建立數據庫。python
from __future__ import print_function import mysql.connector from mysql.connecotr 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" ) # 定義一個函數,建立數據庫並處理建立失敗異常的狀況 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) ################# 主流程 ######################### # 鏈接數據庫 cnx = mysql.connector.connect(user='scott') # 得到 cursor cursor = cnx.cursor() # 開始建立一個數據庫 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.iteritems(): try: print("Creating table {}: ".format(name), end=" ") curosr.execute(dll) except mysql.connecotr.Error as err: if err.errno == errorcode.ER_TABLE_EXISTS_ERROR: print("already exists.") else: print(err.msg) else: print("OK") # 在這裏作其餘處理 # 最後關閉cursor,cnx cursor.close() cnx.close()