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