python MySQLdb手动简单操作源码

来源:互联网 发布:tensorflow 图片分类 编辑:程序博客网 时间:2024/06/18 13:51
#!/usr/bin/pythonimport MySQLdbfrom os import systemclass myDataBaseConnect(object):def insert(self):print "Insert Information:"info_name= str(raw_input("name:"))info_passwd= str(raw_input("passwd:"))info= (info_name, info_passwd)sql= "Insert into " + now_table + "(name, pwd) value(%s, %s)"cur.execute(sql, info)print "Succeedly Insert Information..."def update(self): print "Update Information:"info_name= str(raw_input("name:"))info_new_name= str(raw_input("new name:"))info_passwd= str(raw_input("new passwd:"))info = (info_new_name, info_passwd, info_name)sql = "Update " + now_table + " set name=%s, pwd=%s where name=%s"cur.execute(sql, info)print "Succeedly Update Information..."def delete(self):print "Update Information:"info_name= str(raw_input("name:"))info = (info_name, )sql = "Delete from " + now_table + " where name=%s"cur.execute(sql, info)print "Succeedly Delete Information..."def select(self):"Go through INfomation:"sql = "select * from %s" % now_tablecur.execute(sql)info = cur.fetchall()for id, name, passwd in info:print "name:%-10s  passwd:%-20s" % (name, passwd)print "Connect to your Datebase"now_user= str(raw_input("username:"))now_passwd= str(raw_input("passwd:"))now_host= str(raw_input("host:"))conn = MySQLdb.connect(now_host, now_user, now_passwd)now_db= str(raw_input("DataBaseName:"))conn.select_db(now_db)print "Welcome to your database %s" % now_dbnow_table = str(raw_input("Tables:"))while True:print "1.Insert information"print "2.Update information"print "3.Delete information"print "4.Search information"choice = int(raw_input("Your Choice(0 to quit):"))#while isinstance(choice, str):#choice = raw_input("Error.Please input Correctly!\nYour Choice:")#choice = int(choice)while choice > 4 or  choice < 0 :choice = int(raw_input("Error.Please input Correctly!\nYour Choice:"))print "choice : %d " % choicecur = conn.cursor()my_database = myDataBaseConnect()#choice_option = {#1:my_database.insert(),#2:my_database.update(),#3:my_database.delete(),#4:my_database.select(),#}#result = choice_option.get(choice)#print resultif choice == 1:my_database.insert()elif choice == 2:my_database.update()elif choice == 3:my_database.delete()elif choice == 4:my_database.select()else :breakconn.commit()raw_input("AnyKey to Continue...")#clear the screensystem("clear")cur.close()conn.close()print "Good bye"


原创粉丝点击