目前我正在为学生音乐课程规划师使用数据库。
每当我从数据库中删除一名学生,然后我添加一名新学生为什么不添加ID为1的新学生?
添加数据的代码如下:
def add():
add = 'y'
while add == 'y':
Name = input("Please enter the name of the student: ")
Year = int(input("Please enter the students year: "))
Student = (Name,Year)
insert_data(Student)
print("New data added")
print()
add = input("Do you wish to add another student? (y/n) ")
display = menu.Menu.DisplayMenu("Student") #Adding student name to menu
choice = GetMenuChoice() #Getting the user's menu choice
ValidateMenuChoice(choice) #Validating that user choice
main(choice) #Passing in choice into the main variable
def insert_data(values):
with sqlite3.connect("records.db")as db:
cursor = db.cursor()
sql = "Insert into Student(Name,Year)values(?,?)"
cursor.execute(sql,values)
db.commit()
,数据库代码为:
def create_student_table():
sql = """create table Student
(StudentID integer,
Name string,
Year integer,
primary key(StudentID))"""
create_table(db_name,"Student",sql)
非常感谢任何帮助!
答案 0 :(得分:2)
这就是大多数数据库的工作方式;序列只生成 new 值,而不是重用旧值。
这更有效率(不必搜索免费ID)和一个好主意。想象一个集成了多个部分的系统,包括您的数据库。然后,您刚删除的用户ID仍可在其他系统中引用。如果您的数据库在创建新用户时重用 ID,那么突然那些外部系统会引用新用户,从而导致难以解决的错误。
如果必须重复使用数字,那么您必须指定一个明确使用的ID,而不是让数据库为您选择一个。在这种情况下,您必须找到自己的“缺失”数字,如果您使用来自多个线程或进程的数据库,那么很难。
另请参阅SQLite auto-incrementation documentation,了解有关如何影响新值的选择的更多细节;您可以获得单调递增的数字(可能会产生差距),或者,如果您添加AUTOINCREMENT
关键字,则可以保证值为'使用过的最高值加1'。
请注意,默认行为是自动生成比正在使用的 值高1的ROWID
:
如果插件上未指定
ROWID
,或者指定的ROWID
的值为NULL
,则会自动创建相应的ROWID
。通常的算法是在插入之前为新创建的行 aROWID
提供一个大于表中最大ROWID
的行。只要您从未使用最大ROWID值,上述正常
ROWID
选择算法将生成单调递增的唯一ROWIDs
,并且您永远不会删除表中具有最大值{{ {1}} 即可。如果您删除行或者创建了一个最大可能ROWID
的行,那么在创建新行时可能会重用先前删除的行中的ROWID
,而新创建的ROWIDs
可能不会严格按升序排列。
强调我的。