pymysql insert only if not present
P粉956441054
P粉956441054 2024-02-26 15:39:51
0
1
336

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粉956441054
P粉956441054

reply all(1)
P粉811349112

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...

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template