AttributeError:'DB_Connector'对象没有属性'cursor'

时间:2016-11-16 06:39:09

标签: python-3.x

我是python的新手,并尝试为数据库连接创建一个类对象。当我试图从一个在类中的另一个函数中创建的函数访问变量时,我似乎遇到了麻烦。这是可能的还是我以错误的方式去做?最后一行的代码错误:db_results = oyn_conn.Execute(query),标题中列出了AttributeError

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)

1 个答案:

答案 0 :(得分:0)

好吧所以我玩了它并找到答案,我的代码中有一些sytax错误:

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