python-3.x - 如果指定 Null 值,如何防止 sqlite3 自动增加主键?
问题描述
所以,我正在Python
使用Tkinter
.
现在,当用户将(即主键)标签小部件留空并尝试插入数据时,我将插入而不是空字符串,我想抛出一个但数据被插入自动递增的卷号价值。如果卷号标签小部件留空,我不希望插入主键。
Roll Number
None
Error
这是我用于创建表的代码
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")
解决方案
使用简单的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')
推荐阅读
- java - 从 JSR223 断言读取响应到 Java 代码
- php - PHP 致命错误:未捕获的错误:在 null 上调用成员函数
- json - 如何在 dart/flutter 中正确序列化/反序列化地图?
- android - 如何在 Android 平台(armv7 和 arm64)上使用(编译)Tesseract 4
- google-apps-script - 如何限制发送相同文本的多个表单?
- json - 该对象的 Typescript 接口是否正确?
- opencv - TypeError:integer argument expected int got float in opencv circle
- .net - 使用 VB.NET 上传 AWS S3 文件
- python - 语法错误:Codeskulptor 中的错误标记“”
- lua - 释放 LMB 时如何将 MoveMouseRelative 反转到确切的第一个位置