In Go, you can use database/sql package to establish a connection with a database and execute SQL queries. To check if a record exists and insert it if it doesn't, you can follow these steps:
Open a database connection and ensure it's functional:
db, err := sql.Open("mysql", "user:password@tcp(hostname:port)/database") if err != nil { // Handle error gracefully } err = db.Ping() if err != nil { // Handle error gracefully }
Prepare the SQL query to check record existence:
stmt, err := db.Prepare(`SELECT COUNT(*) FROM table_name WHERE column_name = ?`) if err != nil { // Handle error gracefully }
Execute the query using a specific parameter (e.g., "construction" as column value):
var count int err = stmt.QueryRow("construction").Scan(&count) if err != nil { // Handle error gracefully }
Check the value of count:
If the record doesn't exist (count is 0), prepare the SQL query for insertion:
stmt, err := db.Prepare(`INSERT INTO table_name (column_name) VALUES (?)`) if err != nil { // Handle error gracefully }
Execute the insertion query:
_, err = stmt.Exec("construction") if err != nil { // Handle error gracefully }
By following these steps, you can effectively check for record existence and insert a new record if it's missing using Go's database/sql package.
The above is the detailed content of How to Insert Records in Golang Only if They Don't Already Exist?. For more information, please follow other related articles on the PHP Chinese website!