'AttributeError: 'DB_Connector' object has no attribute 'cursor'
I'm a newbie to python and trying to create a class object for a database connection. I seem to be running into trouble when trying to access a variable from one function that was created in another function inside the class. Is this possible or am I going about it the wrong way? The code errors on the last line: db_results = oyn_conn.Execute(query) with an AttributeError listed in the heading
class DB_Connector(object):
def __init__(self, user,passwd,db):
self.user = user
self.passwd = passwd
self.db = db
self.CreateConnection
def CreateConnection(self):
self.cursor = mysql.connector.connect(user=self.user,password = self.password,database= self.db)
def Execute(self, sql_statement):
self.cursor.execute(sql_statement)
return self.cursor.fetchall()
query = "select venue_name,venue_id from venue where venue_id in('1435','345')"
oyn_conn = DB_Connector('root','password','oyn_db')
db_results = oyn_conn.Execute(query)
Solution 1:[1]
Ok So I played around with it and found the answer, I had some sytax errors in my code:
class DB_Connector(object):
def __init__(self, user,passwd,db):
self.user = user
self.passwd = passwd
self.db = db
self.CreateConnection()
def CreateConnection(self):
self.cnx = mysql.connector.connect(user=self.user,passwd = self.passwd,database= self.db)
self.cursor = self.cnx.cursor()
self.cnx._open_connection()
def Execute(self, sql_statement):
self.cursor.execute(sql_statement)
return self.cursor.fetchall()
def DestroyConnection(self):
self.cursor.close()
query = "select venue_name,venue_id from venue where venue_id
in('1332343501255','1888841136809')"
oyn_conn = DB_Connector('root','password','oyn_db')
db_results = oyn_conn.Execute(query)
print(db_results)
oyn_conn.DestroyConnection()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MattP |
