Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On duplicate key update feature in H2

Tags:

sql

h2

I have developed java desktop application with the use of H2(Embedded). I just have basic knowledge about database, so i simply installed H2 and create a schema name RecordAutomation and then add tables to that schema. Now i am trying to use the ON DUPLICATE KEY UPDATE feature for a specific table which is not working giving sql syntax error, i check my query i found it right, given below

INSERT INTO RECORDAUTOMATION.MREPORT 
(PRODUCTID ,DESCRIPTION ,QUANTITY ,SUBTOTAL ,PROFIT ) 
VALUES (22,olper,5,100,260) 
ON DUPLICATE KEY UPDATE SET QUANTITY = QUANTITY+5;

i search and try to solve this problem some where it is discussed like this feature does not work for non-default tables. i have no idea about default and non-default. please make help me

like image 414
rockledgeDev Avatar asked Apr 22 '15 21:04

rockledgeDev


People also ask

What is on duplicate key update?

ON DUPLICATE KEY UPDATE is a MariaDB/MySQL extension to the INSERT statement that, if it finds a duplicate unique or primary key, will instead perform an UPDATE. The row/s affected value is reported as 1 if a row is inserted, and 2 if a row is updated, unless the API's CLIENT_FOUND_ROWS flag is set.

What is on duplicate key?

The Insert on Duplicate Key Update statement is the extension of the INSERT statement in MySQL. When we specify the ON DUPLICATE KEY UPDATE clause in a SQL statement and a row would cause duplicate error value in a UNIQUE or PRIMARY KEY index column, then updation of the existing row occurs.


1 Answers

You need to use the MySQL mode. To do that, append ;mode=MySQL to the database URL. (This feature is not properly documented yet).

The table needs to have a primary key or at least a unique index. Complete example:

drop table MREPORT;

set mode MySQL;

create table MREPORT(PRODUCTID int primary key, 
DESCRIPTION varchar, QUANTITY int,  SUBTOTAL int, PROFIT int);

INSERT INTO MREPORT 
(PRODUCTID ,DESCRIPTION ,QUANTITY ,SUBTOTAL ,PROFIT ) 
VALUES (22,'olper',5,100,260) 
ON DUPLICATE KEY UPDATE QUANTITY = QUANTITY+5;
like image 93
Thomas Mueller Avatar answered Oct 22 '22 12:10

Thomas Mueller