Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

db.Exec() not returning correct RowsAffected() value in golang for SQL Server

Tags:

sql

sql-server

go

I have written a Golang code to update the records in a table. In this, I have used db.Exec(query) function to execute the query and get the result back. I also want to check the no of rows affected by the query. For this, I have used result.RowsAffected(). But I am not getting the correct no of rows affected.

Below is my Golang Code

func updateTable(dbconnection *sql.DB, query string) (int64, error) {

    println("\n------------------Executing update Query---------------------")

    query = `UPDATE [IMBookingApp].[dbo].[User] 
                    SET Password='xyz'
                    WHERE UserId=2 OR UserId=22 OR UserId=23`    

    result, err := dbconnection.Exec(query)
    if err != nil {
        fmt.Println("Error updating row: " + err.Error())
        errorMsg := errors.New("DATABASE ERROR - " + err.Error())
        return 0, errorMsg
    }

    RowsAffected, err := result.RowsAffected()
    if err != nil {
        fmt.Println("RowsAffected Error", err)
    }

    fmt.Println("Table updated successfully. Rows Affected:", RowsAffected)
    return RowsAffected, nil
}

The output I am getting is as below:-

    Table updated successfully. Rows Affected: 7

In the above SQL query, For the condition - WHERE UserId=2 OR UserId=22 OR UserId=23 output is Rows Affected: 7 However, I should be 3 or less than 3 because UserId is a primary key.

On SSMS, I am getting correct result for the same query - enter image description here

Similarly, for WHERE UserId=2 output is Rows Affected: 5

WHERE UserId=2 OR UserId=22 output is Rows Affected: 6

WHERE UserId=2 OR UserId=22 OR UserId=23 output is Rows Affected: 7

WHERE UserId=2 OR UserId=22 OR UserId=23 OR UserId=24 output is Rows Affected: 8

and "Rows Affected" goes on incrementing by 1 each time.

I have no idea what's going on. I would appreciate if anyone can help me point out the issue with the code.

EDIT

I have also tried to use db.Query(query) as below to find the affected rows, still, I am getting wrong no of affected rows.

rows, err := dbconnection.Query(query)
    if err != nil {
        panic(err)
    }

    var RowsAffected int
    for rows.Next() {
        RowsAffected += 1
    }

    if err := rows.Err(); err != nil {
        panic(err)
    }
    print("RowsAffected:", RowsAffected)
like image 853
Rahul Satal Avatar asked Sep 15 '26 14:09

Rahul Satal


1 Answers

I think u're using SQL Server....

DECLARE @RowCount1 AS INT
 /* Your Update Query Will be Here.. */
 SELECT @RowCount1 = @@ROWCOUNT
 PRINT @RowCount1 --Here u will get Number affected by above Query...
like image 133
THE LIFE-TIME LEARNER Avatar answered Sep 17 '26 16:09

THE LIFE-TIME LEARNER



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!