import mysql.connector
from mysql.connector import errorcode
# 配置数据库连接参数
config = {
'user': 'root',
'passwd': '',
'host': '127.0.0.1',
'database': 'test',
'raise_on_warnings': True,
}
# 尝试连接数据库
try:
conn = mysql.connector.connect(**config)
# 数据库连接的异常处理
except mysql.connector.Error as errObj:
if errObj.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print('数据库连接的用户名或者密码错误')
elif errObj.errno == errorcode.ER_BAD_DB_ERROR:
print('数据库不存在')
else:
print(errObj)
else:
cursor = conn.cursor() # 建立游标
# 数据库操作块
cursor.close() # 关闭游标
conn.close() # 关闭数据库连接
2、在数据库中创建表
# SQL建表语句
TABLES = {}
TABLES['demo_f'] = (
"CREATE TABLE `demo_f` ("
" `emp_no` int(11) NOT NULL AUTO_INCREMENT,"
" `name` char(16) NOT NULL,"
" PRIMARY KEY (`emp_no`)"
") ENGINE=InnoDB"
)
TABLES['demo_new'] = (
"CREATE TABLE `demo_new` ("
" `emp_no` int(11) NOT NULL AUTO_INCREMENT,"
" `name` char(16) NOT NULL,"
" PRIMARY KEY (`emp_no`)"
") ENGINE=InnoDB"
)
for name, ddl in TABLES.items():
try:
print("Creating table {}:".format(name), end='')
cursor.execute(ddl)
except mysql.connector.Error as err:
if err.errno == errorcode_ER_TABLE_EXISTS_ERROR:
print('数据库已经存在')
else:
print(err.errmsg)
else:
print('OK')
3、数据库插入数据
sql = ("INSERT INTO demo_f"
"(emp_no, name)"
"VALUES (%s, %s)")
data = ('2', 'adcd');
cursor.execute(sql, data)
# 提交数据执行
conn.commit()