【问题标题】:How to insert record where is not exists and if exists ignore it by using mysql or knex and express js如何在不存在的地方插入记录,如果存在则通过使用mysql或knex和express js忽略它
【发布时间】:2019-10-13 00:01:38
【问题描述】:

如果值已经存在,我想检查我的数据库,然后不要添加相同的值,如果不存在则添加这个新值。

我的代码

router.post('/additem', function(req, res, next){
  db('types').insert({type_name: req.body.getypename}).where('type_name', '!=', req.body.getypename).then(()=>{
     res.redirect('/additem?success=1')
  }).catch((err)=>{ res.redirect('/additem?'+err) })
})

【问题讨论】:

    标签: mysql express knex.js


    【解决方案1】:

    欢迎来到 Stackoverflow!

    使用.count() 是在添加记录之前检查记录是否存在的一种方法。请参阅下面的函数 countTypeNameRec 作为示例。

    下面的函数addTypeNameRec然后把count和insert放在一起,首先检查记录的数量,如果为零,就添加记录。

    有关使用.count() 的更多详细信息,请参阅the Knex .count() reference。 (对于大型未索引表,使用select * where xxx limit 1 可能是更好的性能选择。)

    第二种方法: 我认为这是一个硬性规则,您不能拥有具有重复的 'type_name' 字段值的 'type' 表记录。如果是这种情况,那么通过数据库中的 SQL 表定义将该字段作为主键(或在该字段的表上创建唯一索引)也将防止用户创建重复记录。在这种情况下,.insert() 语句将在重复记录上引发错误。但是,如果您想给用户一个可以理解的“值已经存在”错误消息,那么解释错误有点混乱。 Here 是关于该问题的讨论。

    如果您不关心向用户返回他们可能无法理解的丑陋原始数据库错误,那么您可以以一种简单的方式使用第二种方法,只需从路由代码中调用 insertTypeNameRec 函数addTypeNameRec 函数(跳过计数检查)。

    守则

    // count the records
    //
    function countTypeNameRec(input_type_name) {
       return db('types')
        .count('*')
        .where('type_name', input_type_name)
        .then((data)=>{
                return data[0].count
            })
    }
    
    // insert a new record
    //
    function insertTypeNameRec(input_type_name) {
       return db('types')
        .insert({type_name: input_type_name})
    }
    
    // Combine the count & insert - the real goal
    //
    function addTypeNameRec(input_type_name) {
    
       return countTypeNameRec(input_type_name)
         .then((rec_count) => {
            if (rec_count===0) {
                insertTypeNameRec(input_type_name) 
            } else {
                // we can return an already exists error from here
            }
         })
    }
    
    // Web routing code
    //
    router.post('/additem', function(req, res, next){
    
       const input_type_name = req.body.getypename;
       // we could validate our input here
    
       // for simplistic second method - call insertTypeNameRec() here instead
       return addTypeNameRec(input_type_name)
          .then(()=>{
                res.redirect('/additem?success=1')
           })
           .catch((err)=>{ 
                res.redirect('/additem?'+err) 
           })
    })
    
    // disclaimer: this code has not been tested
    

    免费赠品(即对您没有询问的事情的 cmets)... 我倾向于尝试将我的能力分解为尽可能小的部分/功能。然后对每个部件进行故障排除和测试变得超级简单。我特别尝试在数据库和通信层分离代码。然后很容易将 Web 请求存根,并将它们与其他服务器处理分开测试。

    【讨论】:

      猜你喜欢
      • 2012-03-28
      • 2012-06-09
      • 1970-01-01
      • 1970-01-01
      • 2016-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多