Python Forum

Full Version: How to insert data if not exists in mysql?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi...I want to insert the new data if it is not exist in MySQL. This is the code:

mySql_insert_query = """INSERT INTO sent (q,polarity,senti) SELECT * FROM (SELECT %s,%s,%s) AS tmp
WHERE NOT EXISTS (SELECT q FROM sent WHERE q = q) LIMIT 1; """
         
            records_to_insert = [(str(row),float(sentiment_dict['compound']), str(sentiment))]

            cursor = connection.cursor()
            cursor.executemany(mySql_insert_query, records_to_insert)
            connection.commit()
The output that I got is shown below. It can only insert 1 data only, which is ('good'), while ('very bad') cannot insert in the database:
Output:
('good',) 1 Record inserted successfully into table ('very bad',) 0 Record inserted successfully into table
This is my table in MySQL:
---------------------------------------
id q polarity senti
---------------------------------------
1 ('good') 0.4404 positive


**Hope you can help me as I am a new learner. Thank you