简体   繁体   中英

Python using sqlite3 to create two tables with foreign keys?

I'm coding a small function to help with learning how to use python and sqlite3 together. In this function I want to create a table for vocabulary words and a separate but, linked table for the word's definitions.

I have this:

import sqlite3

con = sqlite3.connect'words.db'
with con:
    cur = con.cursor()
    cur.execute("CREATE TABLE vocab(vocab_id INTEGER PRIMARY KEY, word TEXT)")

Which works fine my trouble is when I try to create a separate table for the definitions.

I would continue the next line right under the code above like this:

    cur.execute("CREATE TABLE definitions(def_id INTEGER, def TEXT, word_def INTEGER, FOREIGN KEY(word_def) REFERENCES(vocab,vocab_id)")

I was reading the docs for sqlite3 on how to use foreign keys, last part of the this line above was how I thought it was suppose to be done.

This is the returned error message:

<sqlite3.Cursor object at 0xb782b720>
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
sqlite3.OperationalError: near "(": syntax error

I don't know why this is incorrect or how to do it properly. I followed the docs and still get the error?

Your SQL syntax is wrong: REFERENCES should be in the form of table(column) , and you need another closing parenthesis. Try

cur.execute("CREATE TABLE definitions (def_id INTEGER, def TEXT,"
           "word_def INTEGER, FOREIGN KEY(word_def) REFERENCES vocab(vocab_id))")
#                                                             ^     ^         ^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM