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
If you only want to insert a row if it does not exist in the table, you have many options:
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.
Use INSERT .. ON DUPLICATE KEY UPDATE and fake UPDATE operations (for example,
id = id
, whereid
is the primary key).Use INSERT .. SELECT according to WHERE NOT EXISTS. The insert is performed only if the WHERE clause returns TRUE.
There are more options...