Sobes.tech
Junior — Middle

How is data updated in PostgreSQL table rows?

sobes.tech AI

Answer from AI

Updating data in PostgreSQL table rows is done using the SQL query UPDATE. In Go (Golang), this is typically done using the database/sql package along with a PostgreSQL driver, such as lib/pq.

Example of updating a record:

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

func updateUserEmail(db *sql.DB, userID int, newEmail string) error {
    query := `UPDATE users SET email = $1 WHERE id = $2`
    _, err := db.Exec(query, newEmail, userID)
    return err
}

func main() {
    connStr := "user=username dbname=mydb sslmode=disable"
    db, err := sql.Open("postgres", connStr)
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    err = updateUserEmail(db, 1, "newemail@example.com")
    if err != nil {
        log.Fatal(err)
    }
}

Here, db.Exec executes the update SQL query, safely substituting parameters to prevent SQL injection.

How is data updated in PostgreSQL table rows? — Golang - sobes.tech