Python + SQlite3 使用外键
你好!
我正在为我的工作写一个简单的前端界面,用来管理客户数据库。我们只需要一个轻便简单的工具来跟踪客户、任务等等。
这让我有点困惑,因为我正在同时学习Python和SQL,但我想先把外键关系部分搞清楚,然后再继续其他的内容。
我想要实现的是,能够把多个任务分配给一个客户。
这里有个例子:
conn = sqlite3.connect(':memory:')
cur = conn.cursor()
cur.execute('''CREATE TABLE customers (custid INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, phone TEXT, email TEXT, notes TEXT)''')
cur.execute('''CREATE TABLE tasks (taskid INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, notes TEXT, taskcust INTEGER, FOREIGN KEY(taskcust) REFERENCES customer(custid))''')
cur.execute('''INSERT INTO customers (name, phone, email, notes) VALUES('Jeff', '555555', 'jeff@foo.com', 'balblalal')''')
cur.execute('''INSERT INTO tasks (title, notes, taskcust) VALUES ('Toshiba A200', 'replace RAM, add 2 gigs', 1)''')
cur.execute('''INSERT INTO tasks (title, notes, taskcust) VALUES ('WD External HDD', 'Diagnose, tick of death, hdd probably dead', 1)''')
现在我有两个任务分配给了“Jeff”。如果我想打印出Jeff的联系信息和他所有的任务,该怎么做呢?
cur.execute('''SELECT * FROM customers where custid=1''')
for row in cur:
for i in row:
print i
cur.execute('''SELECT * FROM tasks WHERE taskcust=1''')
for row in cur:
for i in row:
print i
我这样做对吗?
1 个回答
2
不要缩进
for row in cur:
for i in row:
print i
在 cur.execute('''SELECT * FROM tasks WHERE taskcust=1''')
下面
除此之外,我觉得其他部分都能按你想要的方式工作。外键很有用,因为现在如果你想找到请求你“更换内存,增加2个G”的客户,你可以追溯到客户的记录。