我想检查记录是否存在,如果不存在,那么我想使用golang将该记录插入数据库

时间:2018-03-23 11:52:31

标签: 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;")

}

4 个答案:

答案 0 :(得分:2)

一种可能的方法是:

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
    }
}

答案 1 :(得分:1)

IGNORE 是你的朋友!

如果您要使用以下查询检查字段的唯一索引,则可以直接使用一个查询执行此操作:

INSERT IGNORE .........;

答案 2 :(得分:0)

我创建了一个函数,可以用来检查用户记录是否存在, 您可以将其重新用于其他表


func userWithFieldExists(field string, value string) bool {
    var count int64
    if err := config.DB.Model(&User{}).Select("id").Where(fmt.Sprintf("%s = ?", field), value).Count(&count).Error; err != nil {
        log.Errorf("unable to retrieved user: %v", err)
        return false
    }
    if count > 0 {
        return true
    }
    return false
}

可以这样使用:

userWithFieldExists("email", user.Email)

答案 3 :(得分:-1)

首先执行select语句。然后用rows.Next()检查数据库上是否有记录。如果没有,请执行插入查询。

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...")
}