我将重复此代码,因此我尝试将其转换为函数。 但我不断收到错误。 的修改 不,我收到错误:缺少1个位置参数:'连接' 在方法中放置“连接”的最佳方法是什么?
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()