简体   繁体   中英

Exception while printing inside a try block

I am trying to print the user ID (int type) and name(varchar type) inside a try block. After enterint details on UID and name, while trying to print the entered value the except block is getting hit. If I remove the print statement from try block. It is working properly. Kindly suggest.

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")

The code is trying to access the variable UID which is not defined:

print("UID : ",UID,"\nname: ",name)
               ^^^

The actual variable the code defined is num :

num = int(input("Enter UID : "))

Change either UID to num or num to UID according to your need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM