Python + SQlite3, using foreign keys
Hi I'm writing this little frontend for a customer database 开发者_开发问答for my workplace. We just needed something light and simple to keep track of customers and tasks and stuff.
This is getting kind of confusing because I'm learning python and SQL at the same time, but I'd like to get the whole foreign key relations part working smoothly before I go on.
What I want to do is be able to have many tasks assigned to 1 customer
here is an example:
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)''')
So now I have 2 tasks assigned to 'Jeff'. What if I want to print Jeff's contact info and all his tasks?
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
am I doing it right?
Don't indent
for row in cur:
for i in row:
print i
below cur.execute('''SELECT * FROM tasks WHERE taskcust=1''')
Besides that, I think it all works the way you want. Foreign keys are useful because now if you want to find the customer who requested you "replace RAM, add 2 gigs" you can trace back to the customer record.
精彩评论