你好
我正在为我的工作场所的客户数据库编写这个小前端。我们只需要一些简单明了的东西来跟踪客户以及任务和东西。
这让我感到困惑,因为我同时学习python和SQL,但是在继续之前,我想让整个外键关系部分顺利进行。
我想做的是能够将许多任务分配给1个客户
这是一个例子:
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)''')
所以现在我有2个任务分配给'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
我做对了吗?
最佳答案
不要缩进
for row in cur:
for i in row:
print i
低于
cur.execute('''SELECT * FROM tasks WHERE taskcust=1''')
除此之外,我认为这一切都可以按照您想要的方式进行。外键非常有用,因为现在,如果您要查找请求您“替换RAM,添加2个演出”的客户,则可以追溯到客户记录。
关于python - Python + SQlite3,使用外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4598300/