以下是python3源码, 需要mysql 5.5及以上环境支持.
当然, 还需要 sudo apt-get install python3-mysql.connector
实现的效果是一个简陋的mysql交互界面
import mysql.connector<span style="white-space:pre"> </span>#导入mysql.connector模块
print("Please enter your username:")
username=input()<span style="white-space:pre"> </span>#将输入存放在username中
print("Please enter your password:")
user_password=input()<span style="white-space:pre"> </span>#将输入存放在user_password中
cnx=mysql.connector.connect(user=username,password=user_password,host='127.0.0.1')
#利用输入的user和password登陆, 默认了host为127.0.0.1
cur=cnx.cursor()<span style="white-space:pre"> </span>#创建Mysql cursor对象
query=input()<span style="white-space:pre"> </span>#开始读入用户在终端的输入
lists=list() #创建一个列表lists
while query!='exit':<span style="white-space:pre"> </span>#当输入不为exit时就一直继续程序
lists=query.split()<span style="white-space:pre"> </span>#对输入进行分词, 并存放在lists列表中
cur.execute(query)<span style="white-space:pre"> </span>#执行刚才的输入
if lists[0]=='select' or lists[0]=='show':<span style="white-space:pre"> </span>#输入的第一个词是select or show
result = cur.fetchall()<span style="white-space:pre"> </span>#取回所需的数据放在result中
for item in result:<span style="white-space:pre"> </span>#对result迭代输出
print(item)
elif lists[0]=='update' or lists[0]=='alter' or lists[0]=='create':<span style="white-space:pre"> </span>#判断第一个词
print("%s success!"%(lists[0]))<span style="white-space:pre"> </span>#输出”xxx success!”
cnx.commit()<span style="white-space:pre"> </span>#最重要的是要进行commit!
elif lists[0]=='insert' or lists[0]=='delete':
print("%s success!"%(lists[0]))
cnx.commit()
elif lists[0]=='use':
print("database changed into %s"%(lists[1]))
query=input()
print("Bye")
cnx.close()
不能语法错误, 一旦错误程序就会报错并退出