整体代码
"""pymysql模拟MySQL命令行
use db;
show tables
show databases;
select;
等一些操作实验
并未实现增删改查等操作
"""
import pymysql
import tabulate
conn = pymysql.connect(
user='root',
password='',
host='localhost',
port=3306,
charset='utf8mb4',
)
cursors = conn.cursor(cursor=pymysql.cursors.DictCursor)
while 1:
sql = input('>>> ').strip()
if sql == 'exit':
break
try:
rows = cursors.execute(query=sql)
except pymysql.err.ProgrammingError as syntax_error:
print(f'\033[1;31m{syntax_error}\033[0m')
conn.rollback()
continue
except pymysql.err.InternalError as op_error:
print(f'\033[1;31m{op_error}\033[0m')
conn.rollback()
continue
if rows is 0:
if sql.split()[0].upper() == 'USE':
print('Database changed')
else:
print(f'Query OK,{rows} affected (0.02sec)')
continue
ls = list()
title_flag = False
while 1:
res = cursors.fetchone()
if not title_flag:
title_flag = True
ls.append(res.keys())
if res is None:
break
ls.append(res.values())
print(tabulate.tabulate(ls, headers='firstrow'))
cursors.close()
conn.close()