# The python module puts the last row id inserted into a variable on the cursorĬ.execute("""INSERT INTO dog VALUES(NULL, 'spot')""")Ĭ. A foreign key means that values in one table must also appear in another table. # Create a connection and cursor to your databaseĬ.execute("""INSERT INTO child VALUES(NULL, 'bobby')""") A foreign key is a way to enforce referential integrity within your SQLite database. The sqlite3 module in python provides a nice little shortcut which saves you from having to run the 'last_insert_rowid()' function explicitly. SELECT last_insert_rowid() - gives the id of spot, assume 4 for this exampleĪlthough your question did not mention python, there is a python tag on this question so I'll assume you want to know how to do this in python. SELECT last_insert_rowid() - gives the id of bobby, assume 2 for this example Here are some example SQL statements for insert: INSERT INTO child VALUES(NULL, 'bobby') Because of the foreign key constraint, an insert into the child_dog table would fail if the child and/or dog referenced do not exist in the database or transaction.You need to know the identifiers of both the child and the dog in order to. Inserts into the child_dog table (known as the mapping table) must happen after inserts into the child and dog tables. This requires three tables: CREATE TABLE child (įOREIGN KEY(child_id) REFERENCES child(id),Īn insert into each of the three tables must be separate SQL statements, but can take place in the context of same transaction. In order to support a child having zero or more dogs and a dog belonging to zero or more children, your database table structure needs to support a Many-To-Many relationship.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |