import sqlite3
def init_db():
conn = sqlite3.connect('students.db')
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER,
grade TEXT
)
''')
conn.commit()
conn.close()
if __name__ == "__main__":
init_db()
]]>
def add_student(name, age, grade):
conn = sqlite3.connect('students.db')
cursor = conn.cursor()
cursor.execute("INSERT INTO students (name, age, grade) VALUES (?, ?, ?)", (name, age, grade))
conn.commit()
conn.close()
def list_students():
conn = sqlite3.connect('students.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()
conn.close()
return rows
]]>
def main_menu():
while True:
print("\n1. 添加学生\n2. 查看所有学生\n3. 退出")
choice = input("请选择操作: ")
if choice == "1":
name = input("姓名: ")
age = int(input("年龄: "))
grade = input("年级: ")
add_student(name, age, grade)
elif choice == "2":
students = list_students()
for student in students:
print(student)
else:
break
if __name__ == "__main__":
main_menu()
]]>
本站知识库部分内容及素材来源于互联网,如有侵权,联系必删!