我可以将这个if语句转换为Python中的函数吗?
我将重复这段代码,所以我尝试将其转换为函数。 但我总是出错。 编辑 否我收到错误:缺少1个位置参数:“连接” 在方法中放置“连接”的最佳方式是什么我可以将这个if语句转换为Python中的函数吗?,python,python-3.x,Python,Python 3.x,我将重复这段代码,所以我尝试将其转换为函数。 但我总是出错。 编辑 否我收到错误:缺少1个位置参数:“连接” 在方法中放置“连接”的最佳方式是什么 def sqlfirst(self, connection): firstname = str(self.first_entry.get()) lastname = str(self.last_entry.get()) license = str(self.lic_entry.get()) if (first
def sqlfirst(self, connection):
firstname = str(self.first_entry.get())
lastname = str(self.last_entry.get())
license = str(self.lic_entry.get())
if (firstname and not lastname and not license): # "You entered first name."
try:
connection = pypyodbc.connect('Driver={SQL Server};Server=;Database=;Trusted_Connection=yes;')
except pypyodbc.Error as ex:
sqlstate = ex.args[0]
if sqlstate == '28000':
self.answer_label['text'] = "You do not have access."
cursor = connection.cursor()
SQLCommand = ("SELECT LASTNAME, FIRSTNAME, L_LICNUMBER "
"FROM dbo. " # table name
"with (nolock)"
"WHERE FIRSTNAME = ?")
Values = [firstname]
cursor.execute(SQLCommand,Values)
return cursor.fetchmany(10)
def calculate2(self):
results = self.sqlfirst()
if results:
self.output1.delete(0, END)
self.output1.insert(0,results[2])
connection.close()
traceback.print_exc()
下面是我的旧代码:
我是否可以将上述内容转换为调用的函数,以便随时调用sqlfirst(self)?我试过:
def sqlfirst(self):
firstname = str(self.first_entry.get())
lastname = str(self.last_entry.get())
if (firstname and not lastname): # "You entered first name."
try:
connection = pypyodbc.connect('Driver={SQL Server};Server=;Database=;Trusted_Connection=yes;')
except pypyodbc.Error as ex:
sqlstate = ex.args[0]
if sqlstate == '28000':
self.answer_label['text'] = "You do not have access."
cursor = connection.cursor()
SQLCommand = ("SELECT LASTNAME "
"FROM dbo.NAME " # table name
"with (nolock)"
"WHERE FIRSTNAME = ?")
Values = [firstname]
cursor.execute(SQLCommand,Values)
results = cursor.fetchmany(10)
def calculate(self):
self.sqlfirst()
if results:
self.output2.delete(0, END)
self.output2.insert(0,results[2])
connection.close()
您可能希望
在函数末尾返回cursor.fetchmany(10)
,而不是将其赋给局部变量,该局部变量在函数退出时丢失。然后像这样调用函数:results=sqlfirst()
。好的,我试试看。顺便说一句,我认为我的大部分问题都来自我的IDE以及它如何使用空格和制表符。我现在正试图搞乱设置。首先,这些不是函数,而是方法。第二,如果您需要有关错误的帮助,请向我们显示错误的回溯。您的类定义在哪里?