How do I use prepared statements using pgx?

Using prepared statements in Go with the pgx library allows you to execute queries efficiently while providing protection against SQL injection. In this example, we showcase how to create a prepared statement, execute it, and handle the results.
go, pgx, prepared statements, database queries, sql injection, golang
package main import ( "context" "fmt" "github.com/jackc/pgx/v5" "log" ) func main() { // Establish a connection to the database conn, err := pgx.Connect(context.Background(), "postgres://username:password@localhost:5432/testdb") if err != nil { log.Fatalln(err) } defer conn.Close(context.Background()) // Prepare a query _, err = conn.Prepare(context.Background(), "insertUser", "INSERT INTO users(name, age) VALUES($1, $2)") if err != nil { log.Fatalln(err) } // Execute the prepared statement _, err = conn.Exec(context.Background(), "insertUser", "John Doe", 30) if err != nil { log.Fatalln(err) } fmt.Println("User inserted successfully!") }

go pgx prepared statements database queries sql injection golang