h24601
h24601

Reputation: 31

NameError: name is not defined when executing class method using variable from constructor

I am attempting to use a variable that was created by the class constructor within a class method. The error message is...

Traceback (most recent call last): File "U.py", line 4, in dbc1.queryDB('select @@version') File "Database.py", line 15, in queryDB _cursor = cnxn.cursor() NameError: name 'cnxn' is not defined

 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))  

I am trying to figure out why the queryDB method cannot see the cnxn variable. According to what I have read a try/catch block in python does not limit the scope of the variable.

Upvotes: 1

Views: 1179

Answers (1)

h24601
h24601

Reputation: 31

I ended up passing the cnxn variable to the queryDB method and it works now. Below is my code.

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))  

Upvotes: 1

Related Questions