Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

mysql

go

package main

import (
    "database/sql"
    "fmt"

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

func main() {

    router := gin.New()
    router.Use(gin.Logger())
    router.Use(gin.Recovery())
    db, err := sql.Open("mysql", "root:password@tcp(gpstest.cksiqniek8yk.ap-south-1.rds.amazonaws.com:3306)/tech")
    if err != nil {
        fmt.Print(err.Error())
    }
    err = db.Ping()
    if err != nil {
        fmt.Print(err.Error())
    }
    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;")

}
like image 814
waseem khan Avatar asked Dec 23 '22 08:12

waseem khan


2 Answers

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
    }
}
like image 197
mkopriva Avatar answered Dec 29 '22 00:12

mkopriva


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...")
}
like image 25
chanioxaris Avatar answered Dec 28 '22 23:12

chanioxaris