본문 바로가기
MySql

MySQL NameError : 전역 이름 'MySQLdb'가 정의되지 않았습니다.

by 베이스 공부 2020. 11. 11.
반응형

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가 무엇인지 이해할 수 없습니다. .


도움이되기를 바랍니다.

 

참조 페이지 https://stackoverflow.com/questions/35712562

 

 

반응형

댓글