I want to insert into my MySQL Workbench database in my python script but I am having issues trying to get it to only insert once if a certain value already exist. So lets say I’m inserting names and the name ‘Bob’ is already in the DB, I don’t want to insert it again at this point.
I’ve been looking at other resources and am currently trying:
for account in accounts: sql = ("If Not Exists(SELECT * FROM Accounts WHERE Account_Name = " + str(account) + ") " "Begin " "INSERT into Accounts (Account_Name, Account_ID, Formatted_Name, Crawler_Name) VALUES (%s, %s, %s, %s) " "End") val = (account, '0', 'test', 'test') mycursor.execute(sql, val) mydb.commit()
where account is some string that isn’t relevant here. I basically want to insert account into the database but only once, if it runs again and the same account is found, i don’t want to re-insert the duplicate (which a regular insert statement will do).
The error i get is:
"mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘If Not Exists(SELECT * FROM Accounts WHERE Account_Name = DE – Kipling DE) Begin’ at line 1"
I’d appreciate any help! 🙂
Source: Python Questions