NameError:全局名称' MySQLdb'没有定义

时间:2016-03-01 00:36:01

标签: python mysql importerror

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     ="john@abc.com"
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

2 个答案:

答案 0 :(得分:0)

您在类文件中定义或导入MySQLdb的位置是什么?粗略的逻辑似乎很好,我只是看不到你在db.py文件中定义或导入MySQLdb的位置。

看起来您正在尝试使用未在类文件范围内定义的符号MySQLdb。

答案 1 :(得分:0)

您需要在 db.py 中导入MySQLdb而不是示例代码,否则在 db.py 中解释器无法理解{{1} }。

您可以查看Python modules了解详情。

希望它有所帮助。

相关问题