2016-03-01 73 views
0

代碼NameError:全局名稱 'MySQLdb的' 沒有定義db.py

class n2b_db: 
    ''' database function class ''' 

    database=connectiox=cursor=server=None 

def __init__(self,server,database): 
    self.database = database 
    self.server  = server 

@classmethod 
def connect(cls,self): 
    self.connectiox = MySQLdb.connect(host=self.server,user="root", passwd="samsam",db=self.database) 
    self.cursor  = self.connectiox.cursor() 
    print("connection successful") 

@classmethod  
def disconnect(cls,self): 
    self.connectiox.close 
    print("connection closed") 

@classmethod 
def query(cls,self, sqlstatement, params): 
    if (params is not None): 
     rtnvalue = self.cursor.execute(sqlstatement, (params,)) 
    else: 
     rtnvalue = self.cursor.execute(sqlstatement) 

    try: 
     self.connectiox.commit() 
     print("transaction committed") 
     return rtnvalue 
    except: 
     self.connectiox.rollback() 
     print("transaction rolled back") 
     return None 

這是示例代碼重現我得到

import MySQLdb 
from passlib.hash import sha256_crypt 
from db import * 
import gc 

username ="John" 
email  ="[email protected]" 
password =sha256_crypt.encrypt((str("john01"))) 

x = n2b_db("localhost","pythondb") 
x.connect() 
n = x.query("""Select * from users where username=%s""",username) 

if int(n)>0: 
    print("That username is already taken, please choose another") 
else: 
    Print("trying to write to sql") 
    n = x.query("""Insert into users(username,password,email,tracking) values (%s,%s,%s,%s)""",username,password,email,"Test tracking") 
    Print("Thanks for registering") 
    gc.collect() 

當我運行錯誤這段代碼我得到如下錯誤,不知道爲什麼我得到這個錯誤。

>>> x.connect() 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/var/www/FlaskApp/FlaskApp/classes/db.py", line 12, in connect 
    self.connectiox = MySQLdb.connect(host=self.server,user="root", passwd="samsam",db=self.database) 
NameError: global name 'MySQLdb' is not defined 

回答

0

您需要在db.py,而不是示例代碼導入MySQLdb,否則db.py解釋無法理解什麼是MySQLdb

您可以檢查Python modules瞭解更多詳情。

希望它有幫助。

0

你在哪裏定義或導入類文件的MySQLdb?邏輯看起來很好,我只是看不到在db.py文件中定義或導入MySQLdb的位置。

它看起來像你正在嘗試使用未在類文件範圍內定義的符號MySQLdb。

+0

是的,你是正確的..我沒有在db.py文件中定義MySQLdb – Yajnas

相關問題