Dan*_*her 1 python mysql dictionary switch-statement
我正在尝试使用字典作为 switch 语句来从用户输入调用各种方法。然而,似乎正在发生的是,无论用户选择什么方法,然后按照它们在我的字典中列出的顺序循环遍历所有方法,而不是在特定方法调用后退出。
我是 Python 的新手,使用过 JAVA,它有一个 switch 语句,并且能够在 python 没有的 switch 中使用 break 关键字。
我一直在研究 stackoverflow 和 google,但在我的特定问题上没有任何运气,因此任何帮助将不胜感激。
完整代码如下:
import pymysql
# Open DB
db = pymysql.connect()
# Prepare a cursor object using cursor() method
cursor = db.cursor()
# Create a Student Table
cursor.execute("DROP TABLE IF EXISTS Student")
cursor.execute("CREATE TABLE Student(Id INT PRIMARY KEY AUTO_INCREMENT, Name VARCHAR(25))")
# Method for inserting new student mySQL
def insert() :
name = input('Enter the Students name: ')
instatmt = "INSERT INTO Student VALUES(NULL, '%s')" % (name)
cursor.execute(instatmt)
db.commit()
return(print("Successfully inserted student"))
# Method for updating a student record mySQL
def update() :
name = input('Enter the Students name: ')
update = input('Enter the Updated name: ')
upstatmt = "UPDATE Student SET Name='%s' WHERE Name='%s'" % (update, name)
cursor.execute(upstatmt)
db.commit()
return(print("Successfully updated object"))
# Method for deleting a student record mySQL
def delete() :
name = input('Enter the Students name: ')
delstatmt = "DELETE FROM Student WHERE Name ='%s'" % (name)
cursor.execute(delstatmt)
db.commit()
return(print("Successfully deleted object"))
# Method for retrieving a student record mySQL
def retrieve() :
name = input('Enter the Students name: ')
retstatmt = "SELECT * FROM Student WHERE Name ='%s'" % (name)
display = cursor.execute(retstatmt)
print(display)
return(print("Object Retrieved..."))
# Call method requested by user
def performAction(argument):
switcher = {
'I': insert(),
'U': update(),
'D': delete(),
'R': retrieve(),
'E': exit
}
func = switcher.get(argument, lambda: "Invalid Entry")
print (func)
# while True :
action = input('Which Operation would you like to perform ( I : Insert, U : Update, D: Delete, R: Retrieve, E: Exit): ')
performAction(action)
# disconnect from server
db.close()
Run Code Online (Sandbox Code Playgroud)
您正在调用函数而不是将它们插入到您的字典中。尝试这个:
def performAction(argument):
switcher = {
'I': insert,
'U': update,
'D': delete,
'R': retrieve,
'E': exit
}
func = switcher.get(argument, lambda: "Invalid Entry")
result = func()
print (func, result)
Run Code Online (Sandbox Code Playgroud)