Sobes.tech
Junior — Middle

How can batch data updates be performed in a database table?

sobes.tech AI

Answer from AI

For batch updating data in a database table in Go, prepared SQL statements with multiple parameters or transactions are usually used to improve efficiency and atomicity.

Example of batch update using database/sql:

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

func batchUpdate(db *sql.DB, updates map[int]string) error {
    tx, err := db.Begin()
    if err != nil {
        return err
    }

    stmt, err := tx.Prepare("UPDATE my_table SET value = $1 WHERE id = $2")
    if err != nil {
        tx.Rollback()
        return err
    }
    defer stmt.Close()

    for id, val := range updates {
        if _, err := stmt.Exec(val, id); err != nil {
            tx.Rollback()
            return err
        }
    }

    return tx.Commit()
}

Here:

  • A transaction is created for batch execution.
  • One update query is prepared.
  • Updates with different parameters are executed in a loop.
  • The transaction is committed at the end.

This approach is more efficient than executing individual queries without a transaction.

If the database supports updating multiple rows with a single query (for example, using CASE WHEN), a complex query can be formed, but this depends on the specific DBMS and task.

How can batch data updates be performed in a database… - sobes.tech