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