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

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

Barbara Streisand
Release: 2024-12-11 06:03:14
Original
520 people have browsed it

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

How to Check for Record Existence and Insert If Not Present in Go

In your Go program, you have a database connection to a MySQL database and a query to check for the existence of a record based on a specific name value. If the record doesn't exist, you want to insert it into the database.

One approach to achieve this is to use a conditional query to perform the check and insertion in one go. Here's how you can do it:

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

    // Check if record exists
    var exists bool
    row := db.QueryRow("SELECT EXISTS(SELECT 1 FROM category WHERE name = 'construction')")
    if err := row.Scan(&exists); err != nil {
        fmt.Print(err.Error())
    }

    // Insert record if not exists
    if !exists {
        if err := db.Exec("INSERT INTO category (name) VALUES ('construction')"); err != nil {
            fmt.Print(err.Error())
        }
    }
}
Copy after login

In this code, we use the QueryRow function to execute the SELECT EXISTS query and store the result in the exists variable. If the value of exists is false, it indicates that the record doesn't exist, and we proceed to insert the record using the Exec function.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template