-1

I have a web app front end that uses nodeJS to facilitate connections and operations on a MySQL backend. I am looking for a way to implement a unique insert that returns an error message if it finds a duplicate key. Is there something I can implement along the lines of:

INSERT INTO clients set ? ON DUPLICATE KEY //SELECT "Error: Duplicate Entry" 
AS "";

From there, what is the best way to retrieve this message and return it to the user on the web front end?

Ray Foo
  • 39
  • 8
  • https://stackoverflow.com/questions/40141332/node-js-mysql-error-handling this might be helpful if you want something to start with – Md. Tazbir Ur Rahman Bhuiyan Sep 22 '17 at 14:33
  • 3
    Possible duplicate of [Node.js MySQL Error Handling](https://stackoverflow.com/questions/40141332/node-js-mysql-error-handling) –  Sep 22 '17 at 15:07

2 Answers2

2

The best way to do it is if you use the SQL Constraint keyword in the creation of the table like bellow:

CREATE TABLE Products (
    Id int NOT NULL,
    Key varchar(40) NOT NULL,
    ...
    CONSTRAINT UC_ID UNIQUE (Key)
);

This way, the server will not allow you at all to insert a duplicate value.

-2
INSERT INTO users
(full_name,
 login,
 password
)
       SELECT 'Mahbub Tito',
              'tito',
              SHA1('12345')
       FROM DUAL
       WHERE NOT EXISTS
       (
           SELECT login
           FROM users
           WHERE login = 'tito'
       );
dbajtr
  • 2,024
  • 2
  • 14
  • 22
ROHIT CHAUHAN
  • 148
  • 1
  • 10
  • thank you for posting the absolutely worst way to possible try and do this! –  Sep 22 '17 at 15:08