Insert data and if already inserted then update in sql

后端 未结 7 3138
眼角桃花
眼角桃花 2021-02-20 13:18

I simply want to insert the data to a SQL database table and if there is some data inserted already then I want to update that data. How can I do this using Java. Kindly help me

7条回答
  •  遇见更好的自我
    2021-02-20 13:51

    The standard SQL statement for INSERT (if new) or UPDATE (if exists) is called MERGE.

    Since you didn't specify which DBMS dialect you're asking about, I'll refer you to the Wikipedia article "Merge (SQL)", which covers most DBMS dialects. Summary:

    MERGE INTO tablename USING table_reference ON (condition)
    WHEN MATCHED THEN
      UPDATE SET column1 = value1 [, column2 = value2 ...]
    WHEN NOT MATCHED THEN
      INSERT (column1 [, column2 ...]) VALUES (value1 [, value2 ...])
    

    Database management systems Oracle Database, DB2, Teradata, EXASOL, CUBRID, MS SQL and Vectorwise support the standard syntax. Some also add non-standard SQL extensions.

    MySQL: INSERT ... ON DUPLICATE KEY UPDATE

    SQLite: INSERT OR REPLACE INTO

    PostgreSQL: INSERT INTO ... ON CONFLICT

提交回复
热议问题