2014-04-04 88 views
1

我在提交插入語句時遇到問題。使用python提交mysql查詢

似乎python不能調用db對象,我不明白爲什麼。

錯誤:

在線self.db.commit()

[-] ERROR: 'NoneType' object has no attribute 'commit' 

代碼:

class Database(object):  
    def __init__(self): 
     self.db = self.db_connect() 

    def db_connect(self): 
     try: 
      self.db = MySQLdb.connect(host=MYSQL_HOST, 
            user=MYSQL_USER, 
            passwd=MYSQL_PWD, 
            db=MYSQL_DATABASE) 
      print '[+] Connected to {db} database'.format(db=MYSQL_DATABASE) 
      self.cur = self.db.cursor() 
     except Exception as e: 
      print '[-] ERROR: ',e 

    def add_email(self, email): 
     try:    
      self.cur.execute('INSERT INTO User (email) VALUES (%s)', (email))   
      self.db.commit() 
      print '[+] Added {email} to User(email) '.format(email=email) 
     except Exception as e: 
      print '[-] ERROR: ',e 
      print '[*] Rolling back' 
      self.db.rollback() 

回答

2

你的功能def db_connect不返回任何東西。意味着它返回None

根據你的代碼

def __init__(self): 
    self.db = self.db_connect() # db_connect return None 

設置self.dbNone,當你嘗試提交,提示錯誤。