Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
sqlite3 foreign key
#1
Newbie with Python. Just downloaded latest ver. 3.6.5. Using sqlite3 (that is loaded with Python) for small work database. Creating one-to-many relationship between 2 tables. Created foreign key constraint but, when I inserted what should be a 'bad' record to my child table, Python did not return an error. So the foreign key is not being enforced. Don't know how to fix this? Here is a simplified version of my commands. With only one record inserted in the transformers table (which will have id = 1), I shouldn't be able to insert a record into the windings table with transformer_id = 4

created the following tables with these 2 commands:
c.execute('CREATE TABLE transformers(id INTEGER PRIMARY KEY, weight INTEGER)')
c.execute('CREATE TABLE windings(id INTEGER PRIMARY KEY, transformer_id INTEGER NOT NULL, \
FOREIGN KEY(transformer_id) REFERENCES transformers(id))')
inserted values into the tables with these 2 commands:
c.execute('INSERT INTO transformers(name) VALUES(4523)')
c.execute('INSERT INTO windings(transformer_id) VALUES(4)')

New to Python and this forum, so I apologize in advance if my post doesn't meet normal format for posts.
Reply
#2
First, because you use the python wrapper to sqlite3, the DBMS does not automatically become part of python, it's still sqlite3,
not Python.
I'd use the sqlite3 interface to open the database and check the schema of the tables in question to make sure the constraints are there.
From command line (in database directory), type slqite3 databasename
at the prompt 'sqlite>' type .schema
check the tables to make sure constraint exists.
Then try to manually insert commands.
.quit to exit
Reply
#3
Quote:c.execute('INSERT INTO transformers(name) VALUES(4523)')
Table transformers has no field named name. Use something like this to insert and then you commit to update the database --> SQLite tutorial http://zetcode.com/db/sqlitepythontutorial/


c.execute('INSERT INTO windings values (?,?)', (transformer_id, 4))
con.commit() 
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  FOREIGN KEY constraint failed SalsaBeanDip 2 2,807 Dec-05-2020, 10:22 PM
Last Post: SalsaBeanDip
  [split] create a virtual keyboard of an unknown foreign language with python fakoly 0 2,414 May-28-2018, 01:34 AM
Last Post: fakoly

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020