How do I use prepared statements using database/sql with MySQL?

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.

Example of Prepared Statements in Go with MySQL

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

prepared statements Go database/sql MySQL SQL injection query performance