NameError:未定义名称“光标”

时间:2020-03-16 19:56:27

标签: python mysql python-3.x pymysql

我正在尝试连接mysql并更改信息,但不起作用。

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

错误

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

我已经定义了游标,但是我想python无法在下一个def中获取信息。任何人都可以帮忙..

1 个答案:

答案 0 :(得分:1)

仅在连接失败时设置cursor,因为您将这些行放在了except:块中。这两行应位于try:块中。

您还需要将db_connection设置为全局,以便可以在其他功能中使用它。

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