Home > front end >  How To Use rows.NextResultSet() in Golang with database/sql?
How To Use rows.NextResultSet() in Golang with database/sql?

Time:12-08

rows.NextRestultSet() is returning false after the first set for rows... The documentation makes this sound straight forward, but it's not working for me. I'm using github.com/denisenkom/go-mssqldb.

Here is an example of my code:

rows, err := db.Query(`
   Query1;
   Query2;
   Query3;
`)

for rows.Next() {
// scan
// check error
}

if !rows.NextResultSet() {
   log.Println("Expected another result set.")
// return some error
}

for rows.Next() ...
// continue process with 2nd result set, but code will not run up until this point

Thank you for any help!

CodePudding user response:

rows.NextResultSet() would return false suggests that there is no next set of rows. You should use it in a do-while structured loop!

for cont := true; cont; cont = rows.NextResultSet() {
  for rows.Next() {
    // scan
    // check error
  }
}

CodePudding user response:

Okay, my mistake was that I was using if rows.Next() instead of for initially because 1. I was only expecting up to one row. 2. I wanted to return an error if there were no rows, and this was the most elegant way of doing that.

The problem is that even if there is one row, calling rows.Next() once will not take you to the end of the rows! This should be obvious since iterating through the rows starts with a call to Next() before reading any data...

So the solution for me, if I know for sure there is only one row, would be to add another rows.Next() before I call rows.NextResultSet(), or to be safe of course a for rows.Next() loop would be best.

Edit: To be clear, I was trying for rows.Next() to test if that was what I was doing wrong. But the error messages at the multiple checks were the same and so I messed up in not realizing that the for loop was solving my problem and the error was being thrown later on...

  • Related