import sqlite3
# 连接数据库(如果不存在则自动创建)
conn = sqlite3.connect('alumni.db')
cursor = conn.cursor()
# 创建alumni表
cursor.execute('''
CREATE TABLE IF NOT EXISTS alumni (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
contact TEXT UNIQUE,
graduation_year INTEGER,
major TEXT
);
''')
# 提交更改并关闭连接
conn.commit()
conn.close()
]]>
def add_alumni(name, contact, year, major):
conn = sqlite3.connect('alumni.db')
cursor = conn.cursor()
cursor.execute('''
INSERT INTO alumni (name, contact, graduation_year, major)
VALUES (?, ?, ?, ?);
''', (name, contact, year, major))
conn.commit()
conn.close()
# 调用函数添加数据
add_alumni('张三', 'zhangsan@example.com', 2010, '计算机科学')
]]>
def list_alumni():
conn = sqlite3.connect('alumni.db')
cursor = conn.cursor()
cursor.execute('SELECT name, contact FROM alumni;')
results = cursor.fetchall()
for row in results:
print(row)
conn.close()
# 调用函数展示数据
list_alumni()
]]>