name 'mydb' is not defined

Question:

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.

Asked By: frky

||

Answers:

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()
Answered By: Leonid Astrin
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.