为了账号安全,请及时绑定邮箱和手机立即绑定

Python从用户输入中检查NULL值,并且不包含在sql更新中

Python从用户输入中检查NULL值,并且不包含在sql更新中

白板的微信 2021-05-06 18:31:53
在我的函数中,我要求用户输入不同的变量,然后更新数据库。问题是,如果他们不输入任何内容,有没有办法我不能将任何内容推送到数据库?当他们不输入var的值时,DB中的值将被清除。db_root = '/var/lib/mysql/'db_to_create = 'students'db_to_use = 'students'conn = pymysql.connect(host='localhost',  user='root', passwd='dbadmin',  cursorclass=pymysql.cursors.DictCursor)print('Connection successful!!')def modify_student():    student_id = input("Enter the id of the student record you wish to modify: ")    student_info = input("Is this student personal information you want to modify - y or n: ")    if student_info == 'y':        firstname = input("Enter the first name: ")        lastname = input("Enter the last name: ")        email = input("Enter the email address: ")        address = input("Enter the address: ")        DOB = input("Enter the DOB in YYYY-MM-DD: ")        cur = conn.cursor()        command = "use %s; " %db_to_use        cur.execute(command)        sql = "UPDATE students_info SET firstname = %s, lastname = %s,  email = %s,  address = %s,  DOB = %s  WHERE ID = %s;"        cur.execute(sql, [firstname, lastname, email, address, DOB, student_id])        print(cur.execute)        conn.commit()        cur.close()        conn.close()    else:        print("else")
查看完整描述

2 回答

?
倚天杖

TA贡献1828条经验 获得超3个赞

您可以使用以下帮助器功能:


def mandatory_input(prompt):

    while True:

        value = input(prompt)

        if value:

            return value

        print("You did not enter the required information.")

并input用它替换所有被认为是强制性的提示,因此:


student_id = input("Enter the id of the student record you wish to modify: ")

变成:


student_id = mandatory_input("Enter the id of the student record you wish to modify: ")

依此类推,以便在用户输入内容之前一直提示用户输入值。


查看完整回答
反对 回复 2021-05-18
  • 2 回答
  • 0 关注
  • 218 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号