0

I am using Python and Sqlite 3 for a program

I have created following two tables in my database

theCursor.execute("""CREATE TABLE IF NOT EXISTS
    taxpayers(txp_id TEXT PRIMARY KEY, name TEXT, type TEXT)""")

theCursor.execute("""CREATE TABLE IF NOT EXISTS
    inventory(txp_id TEXT, item TEXT, hscode TEXT, rate TEXT, qty TEXT, stock TEXT, UNIQUE(txp_id, hscode)
""")

I want to add a unique combination for txp_id and hscode in inventory table. When I run my program and try to add record into inventory, I get this error:

program v6.py", line 217, in addToItemDB
    theCursor.execute("INSERT INTO inventory VALUES(:txp_id, :item, :hscode, :rate, :qty, :stock)",
sqlite3.IntegrityError: UNIQUE constraint failed: inventory.txp_id

Please help

The txp_id is unique for first table

In second table I want to have many hscodes for every txp_id so kept the combination unique so that evey row will be unique even if each of them is not unique in this table.

I add the first record successfully but when I add another record I get this error even if I enter different hscode for same txp_id

4
  • The table already contains a row with that txp_id and hscode (probably from an earlier execution of the program.) Commented Dec 22, 2023 at 17:44
  • I already checked by printing everything in terminal from inventory table. There is no such row already in the table. Commented Dec 22, 2023 at 17:48
  • Actually, looking closer at the error message, it refers ONLY to txp_id, not to the combination of txp_id and hscode. So I'm guessing the inventory table was created with txp_id as a primary key, and you're trying to add another row with the same txp_id. (The code here does not set a primary key on that table, but it uses CREATE TABLE IF NOT EXISTS, which will not replace an existing table definition, so I'm guessing that table was created earlier by different code which did set txp_id as a primary key). Commented Dec 22, 2023 at 17:56
  • I removed the old database and new one generated is working. Commented Dec 23, 2023 at 10:54

0

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.