b114514n 2021-07-16 17:16 采纳率: 0%
浏览 90

为什么我的python文件出现了这个错误?

我在Python中使用sqlite模块中时,出现了NameError: name 'cursor' is not defined错误,代码如下:

# coding=utf-8
import sqlite3 as s

gnlb=['1','2','3','4']
istr1=''
istr2=''

while True:
    gn=input('功能:')
    if gn in gnlb:
        break
    print('没有这个功能,请重新输入。')

try:
    if gn=='1':
        con=s.connect('hey.db')
        cursor=con.cursor()
        sql='SELECT id_1, id_2 FROM Hello_world'
        cursor.execute(sql)
        result_set=cursor.fetchall()
        for row in result_set:
            print('ID1:{0},ID2:{1}'.format(row[0],row[1]))
    elif gn=='2':
        istr1=input()
        istr2=input()
        sql='INSERT INTO Hello_world (id_1, id_2) VALUES (?,?)'
        cursor.execute(sql,[id_1,id_2])
        con.commit()
        print('成功')
except sqlite3.Error as e:
    print('数据发生错误:{}'.format(e))
    con.rollback()
finally:
    if cursor:
        cursor.close()
    if con:
        con.close()

报错内容:
Traceback (most recent call last):
File "nb.py", line 27, in
cursor.execute(sql,[id_1,id_2])
NameError: name 'cursor' is not defined

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "nb.py", line 30, in
except sqlite3.Error as e:
NameError: name 'sqlite3' is not defined

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "nb.py", line 34, in
if cursor:
NameError: name 'cursor' is not defined
求解!

  • 写回答

3条回答 默认 最新

  • 忍气吞声埋头苦干 2021-07-16 17:28
    关注

    如果gn输入的不是1,cursor这个数据库句柄就不会被定义声明,最后自然无法关闭这个连接。

    评论

报告相同问题?

问题事件

  • 创建了问题 7月16日

悬赏问题

  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法
  • ¥15 八路抢答器设计出现故障
  • ¥15 请教一下c语言的代码里有一个地方不懂
  • ¥15 opencv 无法读取视频
  • ¥15 用matlab 实现通信仿真
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档