Python+SQlite3,使用外键

2024-04-18 18:18:04 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨 我正在为我的工作场所的客户数据库写这个小前端。我们只需要一些简单明了的东西来跟踪客户、任务和其他东西。

这有点让人困惑,因为我同时在学习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)''')

所以现在我有两个任务分配给“杰夫”。如果我想打印杰夫的联系方式和所有任务呢?

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

我做得对吗?


Tags: keytextinforexecute客户titleinteger
1条回答
网友
1楼 · 发布于 2024-04-18 18:18:04

不要缩进

    for row in cur:
        for i in row:
            print i

低于cur.execute('''SELECT * FROM tasks WHERE taskcust=1''')

除此之外,我认为一切都是按你所希望的方式进行的。外键很有用,因为现在如果您想找到请求您“替换RAM,添加2个gig”的客户,您可以追溯到客户记录。

相关问题 更多 >