首页 > 解决方案 > 如果指定 Null 值,如何防止 sqlite3 自动增加主键?

问题描述

所以,我正在Python使用Tkinter. 现在,当用户将(即主键)标签小部件留空并尝试插入数据时,我将插入而不是空字符串,我想抛出一个但数据被插入自动递增的卷号价值。如果卷号标签小部件留空,我不希望插入主键。

在此处输入图像描述

Roll NumberNoneError

这是我用于创建表的代码

c.execute("""
    CREATE TABLE students(
    enroll_no integer NOT NULL PRIMARY KEY,
    first_name text NOT NULL,
    middle_name text,
    last_name text,
    course text NOT NULL,
    semester integer NOT NULL
    )
""")

这是插入表格的代码

    try:
        c.execute("INSERT INTO students VALUES (:inp_rn, :inp_fn, :inp_mn, :inp_ln, :inp_course, :inp_semester)",
            {
                'inp_rn':inp_rn.get() if inp_rn.get() != "" else None,
                'inp_fn':inp_fn.get() if inp_fn.get() != "" else None,
                'inp_mn':inp_mn.get() if inp_mn.get() != "" else None,
                'inp_ln':inp_ln.get() if inp_ln.get() != "" else None,
                'inp_course':inp_course.get() if inp_course.get() != "" else None,
                'inp_semester':inp_semester.get() if inp_semester.get() != "" else None
            }
        )
    except sqlite3.IntegrityError:
        messagebox.showerror("Insertion Failed","Insertion Failed")

标签: python-3.xsqlite

解决方案


使用简单的if,else语句来解决此错误。让与卷号相关的输入框。成为e1。将数据库的所有块粘贴到块下面else,也请考虑点赞

if e1.get() == '':
   messagebox.showerror('Please Fill','Please specify roll number to proceed')
else:
................
................

要简单地检查变量是否int()存在,您可以使用.isdigit()which 返回一个布尔值。首先为您分配一个变量,e1.get()然后按照此处进行操作。请记住,只能使用纯数字,任何连字符(-)或特殊字符的使用都会导致else块执行:)

checking = e1.get()
if checking.isdigit() == True:
    .........
else:
    messagebox.showerror('Integrity Error','It must be a integer')

推荐阅读