用sqlite建立日历,用户,记事,课程表
时间: 2023-08-07 09:07:31 浏览: 151
sqlite建库、建表
5星 · 资源好评率100%
好的,以下是使用SQLite建立日历、用户、记事和课程表的示例代码:
1. 创建数据库和表
```python
import sqlite3
# 连接数据库
conn = sqlite3.connect('calendar.db')
# 创建用户表
conn.execute('''CREATE TABLE users
(id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE,
password TEXT NOT NULL);''')
# 创建日历表
conn.execute('''CREATE TABLE calendar
(id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
date TEXT NOT NULL,
event TEXT NOT NULL,
FOREIGN KEY(user_id) REFERENCES users(id));''')
# 创建记事表
conn.execute('''CREATE TABLE notes
(id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
title TEXT NOT NULL,
content TEXT NOT NULL,
FOREIGN KEY(user_id) REFERENCES users(id));''')
# 创建课程表
conn.execute('''CREATE TABLE courses
(id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
course_name TEXT NOT NULL,
course_time TEXT NOT NULL,
FOREIGN KEY(user_id) REFERENCES users(id));''')
# 提交更改
conn.commit()
# 关闭连接
conn.close()
```
2. 插入数据
```python
# 连接数据库
conn = sqlite3.connect('calendar.db')
# 插入用户数据
conn.execute("INSERT INTO users (username, password) VALUES (?, ?)", ('user1', 'password1'))
conn.execute("INSERT INTO users (username, password) VALUES (?, ?)", ('user2', 'password2'))
# 插入日历数据
conn.execute("INSERT INTO calendar (user_id, date, event) VALUES (?, ?, ?)", (1, '2021-11-11', 'Veterans Day'))
conn.execute("INSERT INTO calendar (user_id, date, event) VALUES (?, ?, ?)", (2, '2022-12-25', 'Christmas Day'))
# 插入记事数据
conn.execute("INSERT INTO notes (user_id, title, content) VALUES (?, ?, ?)", (1, 'Note 1', 'This is the first note.'))
conn.execute("INSERT INTO notes (user_id, title, content) VALUES (?, ?, ?)", (2, 'Note 2', 'This is the second note.'))
# 插入课程表数据
conn.execute("INSERT INTO courses (user_id, course_name, course_time) VALUES (?, ?, ?)", (1, 'Math', 'Monday 10:00-11:30'))
conn.execute("INSERT INTO courses (user_id, course_name, course_time) VALUES (?, ?, ?)", (2, 'English', 'Wednesday 13:00-14:30'))
# 提交更改
conn.commit()
# 关闭连接
conn.close()
```
3. 查询数据
```python
# 连接数据库
conn = sqlite3.connect('calendar.db')
# 查询所有用户
users = conn.execute("SELECT * FROM users").fetchall()
print("Users:")
for user in users:
print(user)
# 查询所有日历事件
calendar_events = conn.execute("SELECT * FROM calendar").fetchall()
print("Calendar Events:")
for event in calendar_events:
print(event)
# 查询所有记事
notes = conn.execute("SELECT * FROM notes").fetchall()
print("Notes:")
for note in notes:
print(note)
# 查询所有课程表
courses = conn.execute("SELECT * FROM courses").fetchall()
print("Courses:")
for course in courses:
print(course)
# 关闭连接
conn.close()
```
以上代码只是示例,你可以根据自己的需求进行修改和扩展。
阅读全文