Reputation: 13
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).
Upvotes: 0
Views: 546
Reputation: 853
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, cursor
is variable which below to method, only self.cursor
can store cursor to class, and then other methods can use.
Upvotes: 0
Reputation: 9704
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])
Upvotes: 2