NameError:使用构造函数中的变量执行类方法时未定义名称

时间:2019-01-23 22:56:38

标签: database-connection python-3.7

  

我正在尝试使用由类创建的变量   类方法中的构造函数。错误消息是...

     

回溯(最近一次通话最后一次):文件“ U.py”,第4行,在       dbc1.queryDB('select @@ version')文件“ Database.py”,第15行,在queryDB中       _cursor = cnxn.cursor() NameError:未定义名称“ cnxn”

 U.py contains...  
 import Database   
 dbc1 = Database.Database('server','dbname')  
 dbc1.queryDB('select ')  
 name = input('Pres the return key to kill the database connection...')  

Database.py contains...  
import pyodbc  
import sys  

class Database:  
     def __init__(self, server, database):  
        try:  
            cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';Trusted_Connection=yes')  
        except Exception as e:  
            print("Database Connection Error: " + str(e))  


def queryDB(self,sql):  
    _cursor = cnxn.cursor()  
        try:            
           _cursor.execute(sql)  
        except Exception as e:              
           print("SQL Execution Error: " + str(e))  

我试图弄清楚为什么queryDB方法看不到cnxn变量。根据我所读的内容,python中的try / catch块并不限制变量的范围。

1 个答案:

答案 0 :(得分:0)

我最终将cnxn变量传递给queryDB方法,并且现在可以使用了。下面是我的代码。

import Database  

dbc1 = Database.Database('server','database')  
dbc1.queryDB('select @@version',dbc1.cnxn)  
name = input('Pres the return key to kill the database connection...')  

import pyodbc  
import sys  

#I want the database connection to be established at the same time that an instance of the database class is created.  
class Database:  
    def __init__(self, server, database):  
    try:  
        self.cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';Trusted_Connection=yes')  
    except Exception as e:  
        print("Database Connection Error: " + str(e))  

#Methods  
#Execute SQL  
def queryDB(self,sql,cnxn):   
    _cusrsor = cnxn.cursor()  
    try:  
        cnxn.execute(sql)  

    except Exception as e:  
        print("SQL Execution Error: " + str(e))