Python Forum
How to insert data if not exists in mysql?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to insert data if not exists in mysql?
#1
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Mysql and mysql.connector error lostintime 2 612 Oct-03-2023, 10:25 PM
Last Post: lostintime
  Python Serial: How to read the complete line to insert to MySQL? sylar 1 781 Mar-21-2023, 10:06 PM
Last Post: deanhystad
  How to insert different types of data into a function DrData82 0 1,225 Feb-10-2022, 10:41 PM
Last Post: DrData82
  Mysql error message: Lost connection to MySQL server during query tomtom 6 15,684 Feb-09-2022, 09:55 AM
Last Post: ibreeden
  How to read rainfall time series and insert missing data points MadsM 4 2,124 Jan-06-2022, 10:39 AM
Last Post: amdi40
  SaltStack: MySQL returner save less data into Database table columns xtc14 2 2,115 Jul-02-2021, 02:19 PM
Last Post: xtc14
  Reading data from mysql. stsxbel 2 2,164 May-23-2021, 06:56 PM
Last Post: stsxbel
  Getting false even when data exists sriniyum 12 4,182 May-20-2021, 03:29 AM
Last Post: sriniyum
  Insert into mysql through python LaKhWaN 0 1,922 Aug-26-2020, 04:54 AM
Last Post: LaKhWaN
  insert more data at once in MongoDB Leon79 2 2,290 Jul-05-2020, 01:34 PM
Last Post: Leon79

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020