I want to use Sqlite3 with Python and created queries as follows:

import sqlite3
from sqlite3 import Error

db = sqlite3.connect("temp.sqlite")
cursor = db.cursor()

cursor.execute("PRAGMA foreign_keys = ON") #Turns foreign_key support on

cursor.execute("""DROP TABLE IF EXISTS tx""")
cursor.execute("""CREATE TABLE tx (
                    tx_index BIGINT NOT NULL PRIMARY KEY,
                    hash CHAR(64) NOT NULL,
                    rbf INT NOT NULL, 
                    tx_in_value BIGINT NOT NULL,
                    tx_out_value BIGINT NOT NULL

cursor.execute("""INSERT INTO tx VALUES ('1','2','3','11','11')""")
cursor.execute("""INSERT INTO tx VALUES ('2','2','3','11','11')""")

cursor.execute("""DROP TABLE IF EXISTS txin""")
cursor.execute("""CREATE TABLE txin (
                    addr BIGINT NOT NULL,
                    value BIGINT NOT NULL,
                    tx_index BIGINT NOT NULL,
                    FOREIGN KEY (tx_index) REFERENCES tx (tx_index)

list_tuple = []
# Uncommenting the line below will throw an error

cursor.executemany("""INSERT INTO txin VALUES (?,?,?)""", list_tuple)

cursor.execute("""SELECT * FROM tx""")
cursor.execute("""SELECT * FROM txin""")


The above queries, when tested without Python here, works fine but in the Python, execution gives following error:

cursor.execute("INSERT INTO txin VALUES (?,?,?)", insert_trx_in) sqlite3.IntegrityError: FOREIGN KEY constraint failed

It is simpler version of the problem. In real problem, I insert using executemany Any idea?


1 Answer 1


I believe the error was due to the mismatch in the foreign keys that cursor.executemany was trying to insert. If the foreign key to be inserted in TABLE2 is not present in TABLE1 (primary key holder), it throws an error.

It means that if TABLE 1 has 2 values in the primary key column then while inserting values in TABLE2, the values for the foreign key must exactly match to one of the primary key values in the TABLE1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.