NameError: global name 'MySQLdb' is not defined

NameError: global name 'MySQLdb' is not defined

代码 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

您在 class 文件的什么地方定义或导入了 MySQLdb?粗略地看,逻辑似乎很好,我只是看不到文件 db.py.

中定义或导入 MySQLdb 的位置

您似乎正在尝试使用未在 class 文件范围内定义的符号 MySQLdb。

您需要在db.py中导入MySQLdb而不是示例代码,否则在db.py[=21中=] 解释器无法理解什么是 MySQLdb.

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

希望对您有所帮助。