NameError: name 'cursor' is not defined

user12354454 :

I'm trying to connect mysql and change info but isn't work.

main.py

import pymysql

def connect_setting():
    # Trying to connect
    db_connection = None
    try:
        db_connection = pymysql.connect(
        user='db', 
        passwd='password', 
        host='127.0.0.1', 
        db='test', 
        charset='utf8'
        )
       # If connection is not successful
    except:
        print("Can't connect to database")
        return 0
    # If Connection Is Successful
        print("Connected")

    # Making Cursor Object For Query Execution
        global cursor
        cursor = db_connection.cursor()


def get_off():

    sql = '''INSERT INTO `-100`'''

    cursor.execute(sql)
    db_connection.commit()

index.py

from main import get_off as sql

sql()

error

raceback (most recent call last):
  File "/workspace/Kakao_points/index.py", line 3, in <module>
    sql()
  File "/workspace/Kakao_points/main.py", line 30, in get_off
    cursor.execute(sql)
NameError: name 'cursor' is not defined

I already defined cursor but somehow python didn't get info in next def I guess.. anybody please help..?

Barmar :

You're only setting cursor when the connection fails, because you put those lines in the except: block. Those two lines should be in the try: block.

You also need to make db_connection global so you can use it in the other function.

def connect_setting():
    global db_connection
    # Trying to connect
    db_connection = None
    try:
        db_connection = pymysql.connect(
        user='db', 
        passwd='password', 
        host='127.0.0.1', 
        db='test', 
        charset='utf8'
        )

        # Making Cursor Object For Query Execution
        global cursor
        cursor = db_connection.cursor()
        # If Connection Is Successful
        print("Connected")
    # If connection is not successful
    except:
        print("Can't connect to database")
        return 0

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=319596&siteId=1
Recommended