gpt4 book ai didi

python - 名称错误 : global name 'MySQLdb' is not defined

转载 作者:行者123 更新时间:2023-11-29 21:21:11 24 4
gpt4 key购买 nike

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

最佳答案

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

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

希望有帮助。

关于python - 名称错误 : global name 'MySQLdb' is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35712562/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com