开发者社区> 问答> 正文

NameError:名称“ cursor”未定义

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

问题来源:stackoverflow

展开
收起
is大龙 2020-03-23 18:53:41 2205 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
    

    回答来源:stackoverflow

    2020-03-23 18:53:48
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载

相关实验场景

更多