postgresqlgo

How to get the rows affected by an update query and also the returned value from the query?


I'm updating a table with query

sqlStatement := `UPDATE "my_table" SET "column1" = $1 WHERE "column2" = $2 RETURNING "column3"`

row, err := db.ExecContext(ctx, sqlStatement, args...)
if err != nil {
  // handle error
}

rows, err := row.RowsAffected()

is there any way to get the rows affected as well as scan the returned value from update query?


Solution

  • for PostgreSQL you can get results as query result like this:

    sqlStatement := `UPDATE "my_table" SET "column1" = $1 WHERE "column2" = $2 RETURNING "column3"`
    
    rows, err := db.QueryContext(ctx, sqlStatement, args...)
    if err != nil {
      // handle error
    }
    rowsAffected:=0
    defer rows.Close()
    for rows.Next() {
        // Handle result set.
        rowsAffected++
    }
    
    log.Println(rowsAffected)
    
    

    in other databases, to get output from dml statements which affect single row, normally(since go 1.9) we use this syntax as passed arg to statement:

    sql.Named("Arg1", sql.Out{Dest: &outArg})
    

    for your case:

    sqlStatement := `UPDATE "my_table" SET "column1" = $1 WHERE "column2" = $2 RETURNING "column3" INTO $column3`
    
    var column3 string
    result, err := db.ExecContext(ctx, sqlStatement, args..., sql.Named("column3", sql.Out{Dest: &column3}))
    if err != nil {
      // handle error
    }
    
    rowsAffected, err := result.RowsAffected()