search

Home  >  Q&A  >  body text

pymysql insert only if not present

This is my first time using sql and trying to insert data only if the entry is not in the database. My sql looks like this:

insert_query = ("IF NOT EXISTS ( SELECT 1 FROM `follows` WHERE `id_user` = '"+user_id+"' AND `id_folgt` = '"+folgt_id+"') BEGIN INSERT INTO `follows`(`id_user`, `id_folgt`) VALUES ('"+user_id+"','"+folgt_id+"')END;")

Unfortunately I encountered a syntax error

P粉956441054P粉956441054336 days ago364

reply all(1)I'll reply

  • P粉811349112

    P粉8113491122024-02-27 11:19:14

    If you only want to insert a row if it does not exist in the table, you have many options:

    1. Create a unique index through an expression to detect whether it exists. If the value of this expression already exists in the table, the server will prevent the insertion.

    2. Use INSERT .. ON DUPLICATE KEY UPDATE and fake UPDATE operations (for example, id = id, where id is the primary key).

    3. Use INSERT .. SELECT according to WHERE NOT EXISTS. The insert is performed only if the WHERE clause returns TRUE.

    There are more options...

    reply
    0
  • Cancelreply