我在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
求解!
如果gn输入的不是1,cursor这个数据库句柄就不会被定义声明,最后自然无法关闭这个连接。
con=s.connect('hey.db')
cursor=con.cursor()
这两句写在if 语句外面
16,17行放到13行下面,也就是try的外面