如何处理错误:ER_DUP_ENTRY:nodejs中的重复条目

时间:2017-03-13 14:43:23

标签: javascript mysql node.js express

我在mysql数据库中有唯一的列,当发生重复条目时它会给出错误:ER_DUP_ENTRY:重复条目如何处理错误形式nodejs

3 个答案:

答案 0 :(得分:0)

首先,您必须通过选择查询检查重复数据。然后,如果结果长度不为零,则编写插入查询。

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});
                  });   
                  }


              });
          }
       }

});

});

答案 1 :(得分:0)

将保存内容放入try块并捕获所有错误。添加针对重复项的特定检查,其余作为默认处理

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);
    }
}

答案 2 :(得分:0)

如果您使用 sequelize,这会有所帮助:

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;
        }
    }