Search code examples
c#mysqlsqlinsert-query

c# mysql insert query, if record exists then update


I am trying to insert the new records in table, I have two columns

      user_records
 ------------------------
| Attribute |  Datatype  |
|------------------------|
| user_id   | varchar(25)|
| count     | int        |
 ------------------------

Query :

INSERT into user_records Values("nix_1", 0)

but if the user already exists, then it should increase count by 1


Solution

  • Why not use the INSERT ... ON DUPLICATE KEY syntax?

    INSERT INTO user_records (user_id, count) VALUES ('nix_1', 0)
    ON DUPLICATE KEY UPDATE count = count + 1;
    

    http://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html