简体   繁体   English

Python使用sqlite3创建带有外键的两个表?

[英]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. 我正在编写一个小函数,以帮助学习如何一起使用python和sqlite3。 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. 我正在阅读有关sqlite3的文档,了解如何使用外键,上面这一行的最后一部分是我认为应该完成的方式。

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. 您的SQL语法错误: REFERENCES应该采用table(column)的形式,并且您需要另一个右括号。 Try 尝试

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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