Home > database >  name 'mydb' is not defined
name 'mydb' is not defined

Time:02-06

I'd like to access mydb variable on line 15, but it can¨t be seen. Even though I would go for Global variable, it still stays the same.

Code:

import mysql.connector

def connect():
    try:
        mydb = mysql.connector.connect(
        host='localhost',
        user='root',
        password='12345',
        database="Food"
        )   
    except:
        print("Possibly wrong PWD")


mycursor = mydb.cursor()

Error:

NameError: name 'mydb' is not defined

Thanks a lot.

CodePudding user response:

did you call a function? I see you defined it, but don't see where you call it. Try

import mysql.connector

def connect():
    try:
        return mysql.connector.connect(
        host='localhost',
        user='root',
        password='12345',
        database="Food"
        )   
    except:
        print("Possibly wrong PWD")

mydb = connect()
mycursor = mydb.cursor()
  • Related