MySQL Connector/Python 接口 (二)

链接数据库

本文参见这里,示例如何链接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()
相关文章
相关标签/搜索