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

Prepared statements in Go allow you to execute SQL queries efficiently and securely by reusing query plans and preventing SQL injection attacks. Using the `database/sql` package with PostgreSQL, you can easily integrate prepared statements into your application. Here's a simple example of how to use prepared statements with the `database/sql` package in Go.

package main import ( "database/sql" "log" _ "github.com/lib/pq" ) func main() { // Connect to the PostgreSQL database connStr := "user=username dbname=mydb sslmode=disable" db, err := sql.Open("postgres", connStr) if err != nil { log.Fatal(err) } defer db.Close() // Prepare a statement for execution stmt, err := db.Prepare("INSERT INTO users(name, age) VALUES($1, $2)") if err != nil { log.Fatal(err) } defer stmt.Close() // Execute the prepared statement with desired values _, err = stmt.Exec("Alice", 30) if err != nil { log.Fatal(err) } log.Println("User added successfully!") }

prepared statements Go database/sql Postgres SQL injection PostgreSQL example Go database examples