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

前端 未结 3 2012
北恋
北恋 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: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...")
    }
    

提交回复
热议问题