Sobes.tech
Middle

Tell me about SQL injections

sobes.tech AI

Answer from AI

SQL injection is a vulnerability that occurs when user input is improperly handled in SQL queries. An attacker can insert malicious SQL code into the input, which can alter the query logic, for example, gaining access to data, modifying, or deleting it.

In Go, to prevent SQL injections, it is recommended to use prepared statements and parameterized queries, where values are supplied separately from the SQL code.

Example of a safe query using database/sql:

import (
    "database/sql"
    _ "github.com/lib/pq" // PostgreSQL driver
)

func getUserByEmail(db *sql.DB, email string) (*User, error) {
    var user User
    err := db.QueryRow("SELECT id, name FROM users WHERE email = $1", email).Scan(&user.ID, &user.Name)
    if err != nil {
        return nil, err
    }
    return &user, nil
}

Here, $1 is a placeholder for the parameter, which prevents SQL code injection through the email variable.

Tell me about SQL injections — Golang - sobes.tech