Yajnas
Yajnas

Reputation: 53

NameError: global name 'MySQLdb' is not defined

code for 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

this is sample code to reproduce the error i am getting

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()

When i run this code i am getting error as below and not sure why i am getting this error.

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

Upvotes: 1

Views: 14479

Answers (2)

Eric
Eric

Reputation: 2729

You need to import MySQLdb in db.py instead of sample code, otherwise in db.py the interpreter cannot understand what is MySQLdb.

You can check Python modules for more details.

Hope it helps.

Upvotes: 1

Khanal
Khanal

Reputation: 788

Where have you defined or imported MySQLdb on the class file? The logic seems fine on a rough go, I just cannot see where you have defined or imported MySQLdb on the file db.py.

It looks like you are trying to use the symbol MySQLdb that is not defined in the scope of the class file.

Upvotes: 0

Related Questions