import pyodbc
class Database(object):
def connect(self):
connection = pyodbc.connect("""DRIVER={SQL Server};
SERVER=XX\SQLEXPRESS;
DATABASE=ACCOUNT_DBF;
UID=sa;PWD=XXX""")
cursor = connection.cursor()
def check_account(self, usr):
cursor.execute("SELECT * FROM ACCOUNT_TBL WHERE account = ?", usr)
row = cursor.fetchone()
print(row[0])
database = Database()
database.check_account("developer")
So, as you can see I am trying to call the "check_account" function with the parameter of "developer". But whenever I execute/build it, it gives me an error of
"NameError: name cursor not defined"
I am curious and new to python on how to actually do it. I've been searching around the web but I cannot find a specific answer for my problem.
*I am using the latest python btw(3.6.1).
2 Answers 2
The NameError exception is triggered because in the check_account method you can not see local variables defined in connect method.
You need to set instance attributes "inside" self, since you can access self from all methods (it is the instance itself).
def connect(self):
self.connection = pyodbc.connect("""DRIVER={SQL Server};
SERVER=XX\SQLEXPRESS;
DATABASE=ACCOUNT_DBF;
UID=sa;PWD=XXX""")
self.cursor = connection.cursor()
def check_account(self, usr):
self.cursor.execute("SELECT * FROM ACCOUNT_TBL WHERE account = ?", usr)
row = self.cursor.fetchone()
print(row[0])
4 Comments
self first argument where you have the object itself. If you really want to have class methods you have to use @classmethod decorator and the first argument passed will be the Class, not the instance.Try:
class Database(object):
def connect(self):
connection = pyodbc.connect("""DRIVER={SQL Server};
SERVER=XX\SQLEXPRESS;
DATABASE=ACCOUNT_DBF;
UID=sa;PWD=XXX""")
self.cursor = connection.cursor()
In your code, cursoris variable which below to method, only self.cursor can store cursor to class, and then other methods can use.
connect, and even if you did you never return the cursor from that method or assign it to in instance variable, so it is lost.cursor objectas a parameter tocheck_accountfunction