2.3 KiB
2.3 KiB
使用 Connector/Python 创建表
原文:https://overiq.com/mysql-connector-python-101/creating-tables-using-connector-python/
最后更新于 2020 年 7 月 27 日
下面清单中的代码创建了一个数据库和两个表。
import mysql.connector
from mysql.connector import errorcode
from collections import OrderedDict
db = mysql.connector.connect(option_files='my.conf', use_pure=True)
cursor = db.cursor()
db_name = 'blog'
tables = OrderedDict()
tables['category'] = '''
create table category
(
id int not null auto_increment primary key,
name varchar(50) not null
)
'''
tables['post'] = '''
create table post
(
id int not null auto_increment PRIMARY KEY,
title varchar(200) not null,
content text not null,
date TIMESTAMP not null,
category_id int not null,
FOREIGN key (category_id) REFERENCES category(id)
)
'''
def create_db(cursor):
try:
cursor.execute("create database {}".format(db_name))
print("Database created.")
except mysql.connector.Error as err:
print("Database creation failed:", err)
exit(1)
try:
db.database = db_name
print('Database {} already exist.'.format(db_name))
except mysql.connector.Error as err:
# database doesn't exist, create one
if errorcode.ER_BAD_DB_ERROR == err.errno:
create_db(cursor)
db.database = db_name
for k, v in tables.items():
try:
cursor.execute(v)
print('Table {} created.'.format(k))
except mysql.connector.Error as err:
if errorcode.ER_TABLE_EXISTS_ERROR == err.errno:
print('Table {} already exists.'.format(k))
cursor.close()
db.close()
预期输出:
Database created.
Table category created.
Table post created.
工作原理:
-
在第 5-10 行,我们使用
OrderedDict字典而不是常规字典来定义表,这是因为常规字典没有保留元素的顺序。 -
在第 11 行,我们尝试使用连接对象的
database属性来更改数据库。如果数据库不存在,我们调用create_db()来创建数据库。 -
在第 12-20 行,我们通过循环表字典中的项目来创建表。
尝试删除post表,再次运行脚本。这次您将获得以下输出:
Database blog already exists.
Table category already exists.
Table post created.