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;")
}
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
}
}
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...")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With