Insert data and if already inserted then update in sql

后端 未结 7 3137
眼角桃花
眼角桃花 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:48

    Set any field as the unique identity. For an example consider that employee details has to be entered in the table name **EmployeeDetails.**in this case employee_id can be considered as unique.

    use SELECT query select * from EmployeeDetails where employee_id= "the unique keyvalue"; if the resultset is not empty then use UPDATE query to update the fields.

    update EmployeeDetails set Employee_id=?,Full_name=?, Designation=?, Email_id=?, Password=? where Employee_id='" + id + "'"; If the resultset is empty then use the INSERT query to insert the values to the table

    Insert into EmployeeDetails values(...)

    0 讨论(0)
  • 2021-02-20 13:49

    Just identify the unique item in your data set (like Id or a code). Then by using that try to do a SELECT query first. If the Resultset is empty, do the INSERT else try to UPDATE the details.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-02-20 13:55

    You could use the EXISTS keyword to check for the existance of rows:

    IF EXISTS (SELECT TOP 1 * FROM...)
    BEGIN
        UPDATE....
    END
    ELSE
    BEGIN
       INSERT...
    END
    
    0 讨论(0)
  • 2021-02-20 14:00

    you have to first check the data exist in table if exist then use update query otherwise insert data its simple

    0 讨论(0)
  • 2021-02-20 14:07

    try to following way:

    Example Query

    INSERT INTO table (id, name, city) VALUES(1, "ABC", "XYZ") ON DUPLICATE KEY UPDATE
    name="ABC", city="XYZ"

    for more help see documentation. Click here

    0 讨论(0)
提交回复
热议问题