I want to check if record exist and if not exist then i want to insert that record to database using golang

前端 未结 3 2011
北恋
北恋 2020-12-19 23:28
package main

import (
    \"database/sql\"
    \"fmt\"

    \"github.com/gin-gonic/gin\"
)

func main() {

    router := gin.New()
    router.Use(gin.Logger())
             


        
相关标签:
3条回答
  • 2020-12-19 23:53

    IGNORE is your friend!

    You can do it directly with one query if you have a unique index of the field that you want to check with a query like this:

    INSERT IGNORE .........;
    
    0 讨论(0)
  • 2020-12-19 23:57

    First execute the select statement. Then with rows.Next() check if there is a record on the database. If not, execute the insert query.

    rows, err := db.Query("select sum(usercount) as usercount from ( select count(*) as usercount from category where name = 'construction' union all  select count(*) as usercount from sub_category where name = 'construction'  union all  select count(*) as usercount from industry where name = 'construction' ) as usercounts;")
    if err != nil {
        log.Fatal(err)
    }
    
    if rows.Next() {
        //exists
    } else {
        db.Query("INSERT INTO...")
    }
    
    0 讨论(0)
  • 2020-12-20 00:02

    One possible approach would be:

    var exists bool
    row := db.QueryRow("SELECT EXISTS(SELECT 1 FROM ...)")
    if err := row.Scan(&exists); err != nil {
        return err
    } else if !exists {
        if err := db.Exec("INSERT ..."); err != nil {
            return err
        }
    }
    
    0 讨论(0)
提交回复
热议问题