【问题标题】:name 'connection' is not defined名称“连接”未定义
【发布时间】:2017-05-12 15:18:33
【问题描述】:

我正在尝试关闭 ODBC 连接,但我不确定实现此功能的最佳方法。

我的程序正在运行,但我想用connection.close() 正确关闭连接。这是我的原文:

import pypyodbc


def queryfirst():
    return ("SELECT FIRSTNAME, LASTNAME "      
            "FROM dbo.MAIN "
            "WHERE FIRSTNAME = ?")

def sqlfirst():
    firstname = "Josh"
    if True:    
        connection = pypyodbc.connect('Driver={SQL Server};Server=;Database=;Trusted_Connection=yes;')
        cursor = connection.cursor() 
        SQLCommand = queryfirst()
        Values = [firstname]
        cursor.execute(SQLCommand,Values)
        return cursor.fetchmany(2)


def calculate():
    results = sqlfirst()
    if results:
        print (results[0])  # prints the first and last name


calculate()

我试过了:

import pypyodbc


def queryfirst():
    return ("SELECT FIRSTNAME, LASTNAME "      
            "FROM dbo.V_LICMAIN_IT "
            "WHERE FIRSTNAME = ?")

def sqlfirst(closeit):
    firstname = "Josh"
    if True:    
        connection = pypyodbc.connect('Driver={SQL Server};Server=;Database=;Trusted_Connection=yes;')
        cursor = connection.cursor() 
        SQLCommand = queryfirst()
        Values = [firstname]
        cursor.execute(SQLCommand,Values)
        return cursor.fetchmany(1)
        connection.close() = closeit

def calculate():
    results = sqlfirst()
    if results:
        print (results[0])  # prints the first and last name
        sqlfirst(closeit)

calculate()

上面说:

connection.close() = closeit
SyntaxError: can't assign to function call

这没有运气:

import pypyodbc


def queryfirst():
    return ("SELECT FIRSTNAME, LASTNAME "      
            "FROM dbo.MAIN "
            "WHERE FIRSTNAME = ?")

def closeconn():
    return connection.close()

def sqlfirst():
    firstname = "Josh"
    if True:    
        connection = pypyodbc.connect('Driver={SQL Server};Server=;Database=;Trusted_Connection=yes;')
        cursor = connection.cursor() 
        SQLCommand = queryfirst()
        Values = [firstname]
        cursor.execute(SQLCommand,Values)
        return cursor.fetchmany(2)
        testname = closeconn()

def calculate():
    results = sqlfirst()
    if results:
        print (results[0])  # prints the first and last name
        closeconn()

calculate()

上面说:

return connection.close()
NameError: name 'connection' is not defined

更新:以下是我的完整代码:

import os
import pypyodbc
import tkinter
from tkinter import ttk
from tkinter import messagebox
from tkinter import BOTH, END, LEFT
import traceback


class Adder(ttk.Frame):
    """The adders gui and functions."""
    def __init__(self, parent, *args, **kwargs):
        ttk.Frame.__init__(self, parent, *args, **kwargs)
        self.root = parent
        self.init_gui()

    def queryfirst(self):
        return ("SELECT LASTNAME, FIRSTNAME, ID "      
                "FROM dbo.TABLENAME "   # table name
                "WHERE FIRSTNAME = ?")

    def connect(self):
        return pypyodbc.connect('Driver={SQL Server};Server=;Database=;Trusted_Connection=yes;')

    def sqlfirst(self):
        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 = self.connect()
            except pypyodbc.Error as ex:
                sqlstate = ex.args[0]
                if sqlstate == '28000':
                    self.output0.delete(0, END)
                    self.output0.insert(0,"You do not have access.")
            cursor = connection.cursor() 
            SQLCommand = self.queryfirst()
            Values = [firstname]
            cursor.execute(SQLCommand,Values)
            return cursor.fetchmany(10)
#           connection.close()  # !!!!!! <<< this is what I'm working on


    def calculate2(self):
        results = self.sqlfirst()
        if results:
            self.output2.delete(0, END)
            self.output2.insert(0,results[2])



    def calculate1(self):
        results = self.sqlfirst()
        if results:
            self.output1.delete(0, END)
            self.output1.insert(0,results[1])



    def calculate(self):
        results = self.sqlfirst()
        if results:

                self.output0.delete(0, END)
                self.output0.insert(0,results[0])

                self.calculate1()
                self.calculate2()



    def init_gui(self):
        """Builds GUI."""
        self.root.title('Verify')
        self.root.option_add('*tearOff', 'FALSE')


        # Input Boxes and Button

        self.first_entry = tkinter.Entry(self, width=28) # first input box
        self.first_entry.grid(sticky='', column=1, row=1) 



        self.output0 = tkinter.Entry(self, width=150, bd=0,)
        self.output0.grid(column=0, row=6, columnspan=5, padx=10)
        self.output0.bind("<Key>", lambda e: "break")
        self.output1 = tkinter.Entry(self, width=150, bd=0,)
        self.output1.grid(column=0, row=7, columnspan=5, padx=10)
        self.output1.bind("<Key>", lambda e: "break")
        self.output2 = tkinter.Entry(self, width=150, bd=0,)
        self.output2.grid(column=0, row=8, columnspan=5, padx=10)
        self.output2.bind("<Key>", lambda e: "break")

        self.blank.grid(row=16,)      

if __name__ == '__main__':
    root = tkinter.Tk()
    Adder(root)
    root.resizable(width=False, height=False) # locks window from being resized
    root.mainloop()

【问题讨论】:

  • 你也可以发布错误日志吗?
  • 我是否可以通过将 traceback.print_exc() 放入函数中来获得?我用我得到的错误更新了上面的内容。
  • 那么你需要将connection设为全局,因为除非你在课堂上,否则你无法访问它
  • 你能帮我做这件事吗?我在一个班。我在上面的更新中发布了我的完整代码
  • 将连接存储在self.connection,任何方法都可以更容易地引用它。

标签: python pypyodbc


【解决方案1】:

看起来您遇到了异常并将其屏蔽,因为 sqlstate 不是 '28000'

        try:
            connection = self.connect()
        except pypyodbc.Error as ex:
            sqlstate = ex.args[0]
            if sqlstate == '28000':
                self.output0.delete(0, END)
                self.output0.insert(0,"You do not have access.")
            else:
                self.output0.insert(0,"Some other database error ({})".format(
                    ex.message
                ))
        else:
            cursor = connection.cursor() 
            SQLCommand = self.queryfirst()
            Values = [firstname]
            cursor.execute(SQLCommand,Values)
            try:
                return cursor.fetchmany(10)
            finally:
                connection.close()

还要注意,return 语句之后的任何行都不会被执行,除非它位于 finally 块内。

【讨论】:

    猜你喜欢
    • 2018-11-19
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-29
    • 2018-01-24
    相关资源
    最近更新 更多