我正在尝试在try块中打印用户ID(int类型)和名称(varchar类型)。在关于UID和名称的enterint详细信息之后,在尝试打印输入的值时,except块被命中。如果我从try块中删除print语句。它运作正常。请建议。
import mysql.connector
import sys
con = mysql.connector.connect(user='root',password='dream',host='localhost',port='3306',database='arvind')
cursor = con.cursor()
try:
cursor.execute("create table USER_INFO(U_ID bigint,name varchar(20))")
except:
print("table already created\n")
#cursor.close()
#con.close()
#sys.exit();
print("table created successfully :)\n")
#cursor.close()
#con.close()
ch = input("Do you want to inseret data ??? (y/n)")
if ch=='y':
while 1:
try:
num = int(input("Enter UID : "))
#print("num entered ",num)
name = input("Enter U_name : ")
#print("name entered ",name)
print("UID : ",UID,"\nname: ",name)
except:
print("Enter user ID for UID and name for U_name")
continue;
cursor.execute("""INSERT INTO USER_INFO values (%s,%s)""",(num,name))
con.commit()
print("Data inserted in the table")
c = input("Enter 'n' top exit")
print("c : ",c)
if(c == 'n'):
sys.exit();
else:
print("NO")
答案 0 :(得分:2)
代码正在尝试访问未定义的变量UID
:
print("UID : ",UID,"\nname: ",name)
^^^
代码定义的实际变量是num
:
num = int(input("Enter UID : "))
根据您的需要,将UID
更改为num
或num
更改为UID
。