Using prepared statements in Go with the `database/sql` package for MySQL is an important aspect of database interaction as it helps prevent SQL injection and improves query performance. Below is a brief explanation followed by an example of how to implement prepared statements in Go.
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/go-sql-driver/mysql"
)
func main() {
// Connect to the database
db, err := sql.Open("mysql", "user:password@tcp(localhost:3306)/dbname")
if err != nil {
log.Fatal(err)
}
defer db.Close()
// Prepare a statement
stmt, err := db.Prepare("INSERT INTO users(name, age) VALUES(?, ?)")
if err != nil {
log.Fatal(err)
}
defer stmt.Close()
// Execute the prepared statement with actual data
res, err := stmt.Exec("John Doe", 30)
if err != nil {
log.Fatal(err)
}
// Get the result
id, err := res.LastInsertId()
if err != nil {
log.Fatal(err)
}
fmt.Printf("User inserted with ID: %d\n", id)
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?