python3嵌入mysql实现简易交互界面

来源:互联网 发布:网络丢包率标准 编辑:程序博客网 时间:2024/06/08 08:47

以下是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.1cur=cnx.cursor()<span style="white-space:pre"></span>#创建Mysql cursor对象query=input()<span style="white-space:pre"></span>#开始读入用户在终端的输入lists=list()#创建一个列表listswhile 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 showresult = 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()

不能语法错误, 一旦错误程序就会报错并退出

0 0
原创粉丝点击