Python 与 SQLite 中的一对多和多对多关系
在python中使用数据库时,理解表间关系至关重要。本文以wnba为例,探讨一对多和多对多关系在sqlite中的实现方法,并提供python代码示例。
一对多与多对多关系
Python与SQLite的数据库操作
1. 数据库设置
首先,创建一个SQLite数据库并连接:
import sqlite3conn = sqlite3.connect("sports.db") # 创建或连接数据库cursor = conn.cursor()
2. 创建表
创建team、athlete、brand和deal四个表:
cursor.execute("""CREATE TABLE IF NOT EXISTS team ( id INTEGER PRIMARY KEY, name TEXT NOT NULL)""")cursor.execute("""CREATE TABLE IF NOT EXISTS athlete ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, team_id INTEGER, FOREIGN KEY (team_id) REFERENCES team(id))""")cursor.execute("""CREATE TABLE IF NOT EXISTS brand ( id INTEGER PRIMARY KEY, name TEXT NOT NULL)""")cursor.execute("""CREATE TABLE IF NOT EXISTS deal ( id INTEGER PRIMARY KEY, athlete_id INTEGER, brand_id INTEGER, FOREIGN KEY (athlete_id) REFERENCES athlete(id), FOREIGN KEY (brand_id) REFERENCES brand(id))""")conn.commit()
3. 一对多关系:球队和运动员
插入数据并查询:
cursor.execute("INSERT INTO team (name) VALUES (?)", ("New York Liberty",))team_id = cursor.lastrowidcursor.execute("INSERT INTO athlete (name, team_id) VALUES (?, ?)", ("Breanna Stewart", team_id))cursor.execute("INSERT INTO athlete (name, team_id) VALUES (?, ?)", ("Sabrina Ionescu", team_id))conn.commit()cursor.execute("SELECT name FROM athlete WHERE team_id = ?", (team_id,))athletes = cursor.fetchall()print("Athletes on the team:", athletes)
4. 多对多关系:运动员和品牌
插入品牌和交易记录,并查询运动员的品牌:
cursor.execute("INSERT INTO brand (name) VALUES (?)", ("Nike",))brand_id_nike = cursor.lastrowidcursor.execute("INSERT INTO brand (name) VALUES (?)", ("Adidas",))brand_id_adidas = cursor.lastrowidcursor.execute("INSERT INTO deal (athlete_id, brand_id) VALUES (?, ?)", (1, brand_id_nike))cursor.execute("INSERT INTO deal (athlete_id, brand_id) VALUES (?, ?)", (1, brand_id_adidas))cursor.execute("INSERT INTO deal (athlete_id, brand_id) VALUES (?, ?)", (2, brand_id_nike))conn.commit()cursor.execute("""SELECT Brand.nameFROM BrandJOIN Deal ON Brand.id = Deal.brand_idWHERE Deal.athlete_id = ?""", (1,))brands = cursor.fetchall()print("Brands for Athlete 1:", brands)
结论
通过定义外键关系并使用Python进行数据管理,可以创建具有清晰连接的SQLite数据库。理解一对多和多对多关系对于有效构建数据库至关重要。 这个示例仅为入门级,可以扩展到更复杂的关系模型。 记得在操作完成后关闭数据库连接:conn.close()