【问题标题】:NameError: name 'cursor' is not definedNameError:名称“光标”未定义
【发布时间】:2020-06-27 22:44:48
【问题描述】:

我正在尝试连接 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 中没有得到信息我猜..有人请帮忙..?

【问题讨论】:

  • 只有在出现异常时才分配cursor

标签: python mysql python-3.x pymysql


【解决方案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

【讨论】:

  • 我确实改变了和你的一样但仍然相同的错误 NameError: name 'cursor' is not defined
  • 您收到Connected 消息了吗?
  • 是的,我还以为我没有打开 mysql 服务,但它已打开,python 也打印“已连接”。
  • 我想不出理由。我更新了答案说你还需要global db_connection,但这并不影响cursor
  • 嗯,我仍在以另一种方式工作,但输出相同:C
猜你喜欢
  • 2020-05-16
  • 2019-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-24
  • 1970-01-01
  • 2021-04-15
相关资源
最近更新 更多