Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 未定义名称“连接”_Python_Pypyodbc - Fatal编程技术网

Python 未定义名称“连接”

Python 未定义名称“连接”,python,pypyodbc,Python,Pypyodbc,我正在尝试关闭ODBC连接,但我不确定实现这一点的最佳方法 我的程序正在运行,但我希望使用connection.close正确关闭连接。这是我的原件: import pypyodbc def queryfirst(): return ("SELECT FIRSTNAME, LASTNAME " "FROM dbo.MAIN " "WHERE FIRSTNAME = ?") def sqlfirst(): first

我正在尝试关闭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
return connection.close()
NameError: name 'connection' is not defined
这件事没有运气:

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()
上面说:

connection.close() = closeit
SyntaxError: can't assign to function call
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()

看起来您得到了一个异常并屏蔽了它,因为sqlstate不是“28000”


还请注意,返回语句后的任何行都不会执行,除非它位于finally块中。

您也可以发布错误日志吗?我是否可以通过将traceback.print\u exc放入函数中来获得它?我更新了上面的内容,发现了一些错误。那么你需要将连接设为全局连接,因为你不能访问它,除非你在一个班级里。你能在这方面给我一些帮助吗?我在一个班里。我在上面的UPDATEstore中发布了我的完整代码。在self.connection的连接中,从任何方法引用它都会更容易。