Reputation: 598
I have unique column in mysql database when and duplicate entry occur's it gives Error: ER_DUP_ENTRY: Duplicate entry how to handle the error form nodejs
Upvotes: 11
Views: 26931
Reputation: 31
if you are using sequelize this can help:
try {
//here you try to add something in your database;
} catch (error) {
if (error.parent.code === 'ER_DUP_ENTRY') {
//here you can handle this error;
} else {
//here you can handle other errors;
}
}
Upvotes: 1
Reputation: 101
Put the save onto try block and catch all errors. add a specific check for duplicates and handle the rest as defaults
try {
return await this.userProfilesRepository.save(userProfile);
} catch (err) {
if (err.code === 'ER_DUP_ENTRY') {
//handleHttpErrors(SYSTEM_ERRORS.USER_ALREADY_EXISTS);
} else {
//handleHttpErrors(err.message);
}
}
Upvotes: 10
Reputation: 1022
At first you have to check duplicate data by select query. then if your result length is not zero then write your insert query.
router.post('/process', function(req, res, next) {
var mysql= require('mysql');
var connection=mysql.createConnection({
host:'localhost',
user:'root',
password:'',
database:'user',
multipleStatements: true
});
connection.connect(function(err){
if(err)
{
throw err;
}
else
{
console.log("Connected");
var name= req.body.name;
console.log(name);
var email=req.body.email;
console.log(email);
var password=req.body.password;
if (name=="" || email=="" || password=="") {
res.render('process', {flag: false, condition: false,fail:false});
}
else
{
var sql="SELECT * from user where name='"+name+"'";
connection.query(sql, function(err,result){
if(result.length!=0)
{
res.render('process', {name:name, condition:false, fail:false});
}
else
{
var sql="INSERT INTO user VALUES('','"+name+"','"+email+"','"+password+"')";
connection.query(sql, function(err,result){
res.render('process', {name:name, flag: true, condition: true});
});
}
});
}
}
});
});
Upvotes: 0