Sobes.tech
Junior — Middle

Explain what is meant by the method of injecting SQL codes into an application and how to prevent it.

sobes.tech AI

Answer from AI

SQL injection is an attack method where an attacker inserts or injects malicious SQL code into database queries through user input data. This allows unauthorized access to data, as well as modification or deletion of data.

To prevent SQL injections in Go applications, you should:

  • Use prepared statements with parameterization, where values are supplied separately from the SQL code.
  • Avoid string concatenation for forming SQL queries with user data.
  • Use ORM libraries that automatically handle parameters.
  • Validate and filter user input.

Example using a prepared statement in Go:

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

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, the email parameter is passed separately, which prevents the possibility of injecting malicious SQL code.

Explain what is meant by the method of injecting SQL… - sobes.tech