.Maui Blog

Golang – Get the number of rows affected by a Query

How to get the number of rows affected by an update, insert, or delete with Golang.

This example is for the Postgres database.

package main

import (
    "database/sql"
    "fmt"
    _ "github.com/pq-master"
)

func main() {
    dbo, _ := sql.Open("postgres", "user=myusername dbname=mydatabase sslmode=disable password=mypassword host=localhost")
    query := "UPDATE foo SET bar = $1 WHERE bar = $2"
    res, err := dbo.Exec(query, 10, 0)
    
    if err != nil {
        fmt.Println(err.Error())	
    } else {
        count, err2 := res.RowsAffected()  
	    
	if err2 != nil {  
	    fmt.Println(err2.Error())	
	} else {		
            fmt.Println(count)
	}
    }  	 
}

Note: Not every database or database driver may support this.

Exit mobile version