连接数据库
本文参见这里,示例如何连接MySQL 数据库。
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 创建数据库。
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()