How do I avoid SQL injection using database/sql with Postgres?

To avoid SQL injection when using the database/sql package with PostgreSQL in Go, you should use prepared statements. Prepared statements ensure that user input is treated as data and not as executable code, minimizing the risk of SQL injections.

Example of Prepared Statements in Go

The following example demonstrates how to safely query a PostgreSQL database using prepared statements.

package main import ( "database/sql" "fmt" "log" _ "github.com/lib/pq" // PostgreSQL driver ) func main() { // Connect to 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 stmt, err := db.Prepare("SELECT name FROM users WHERE id = $1") if err != nil { log.Fatal(err) } defer stmt.Close() // Execute the statement with user input var id int = 1 // This should be a safe user input var name string err = stmt.QueryRow(id).Scan(&name) if err != nil { log.Fatal(err) } fmt.Println("User Name:", name) }

SQL Injection PostgreSQL Go language Prepared Statements Database security