I am using pyodbc
and requests module to pull data using web api and push it to my database- SQL server
.
I making a requests and make a loop over the response inserting it into my database.
in my table column costc is the unique value
Everything works fine, problem is that sometime i may try to insert costc again and then i get the following error:
pyodbc.IntegrityError: ('23000', '[23000] [Microsoft][ODBC SQL Server Driver][SQL Server]Duplicate key was ignored. (3604) (SQLExecDirectW)')
Here's my code:
conn.cursor()
cursor.execute('''INSERT INTO Containers(costc,container,descritpion)
VALUES(?,?,?)''',(costc,container,description))
conn.commit()
I tried running the following code to avoid duplicates:
conn.cursor()
cursor.execute('''IF NOT EXISTS(SELECT * FROM Containers WHERE costc = VALUES(?))
BEGIN
INSERT INTO Containers(costc,container,descritpion)
VALUES(?,?,?)
END''',(costc,costc,container,description))
but I got the following error:
pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near the keyword 'VALUES'
Any idea how to avoid duplicates?