Home >Backend Development >Golang >How to Efficiently Check for Record Existence and Insert if Absent in Go?

How to Efficiently Check for Record Existence and Insert if Absent in Go?

DDD
DDDOriginal
2024-12-12 15:27:13679browse

How to Efficiently Check for Record Existence and Insert if Absent in Go?

Checking for Record Existence and Inserting if Absent in Go

In the provided Go code, a query is executed to retrieve the sum of user counts from the category, sub_category, and industry tables for the category 'construction'. However, the code doesn't check whether the record exists before executing the query.

To check if a record exists and insert it if it doesn't, a possible approach is:

package main

import (
    "database/sql"
    "fmt"
    "os"

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

func main() {
    router := gin.New()
    router.Use(gin.Logger())
    router.Use(gin.Recovery())
    dbUser := os.Getenv("DB_USER")
    dbPwd := os.Getenv("DB_PASSWORD")
    dbHost := os.Getenv("DB_HOST")
    dbPort := os.Getenv("DB_PORT")
    dbDatabase := os.Getenv("DB_NAME")
    db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", dbUser, dbPwd, dbHost, dbPort, dbDatabase))
    if err != nil {
        fmt.Print(err.Error())
    }
    err = db.Ping()
    if err != nil {
        fmt.Print(err.Error())
    }

    var exists bool
    query := "SELECT EXISTS(SELECT 1 FROM ...)"
    row := db.QueryRow(query)
    if err = row.Scan(&exists); err != nil {
        return err
    }

    if !exists {
        query = "INSERT ...";
        if _, err = db.Exec(query); err != nil {
            return err
        }
    }
}

This code checks if the record exists by executing a query and storing the result in the exists variable. If the record doesn't exist, it proceeds to insert it into the database by executing another query.

The above is the detailed content of How to Efficiently Check for Record Existence and Insert if Absent in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn