How to move the ResultSet cursor to the first row in mysql using golang
Assuming you mean the Resultset
type in https://github.com/siddontang/go-mysql/blob/master/mysql/, then it looks like a result set is loaded entirely into memory and you just access the first row by passing 0 as the column in functions like (*Resultset).GetValue
, (*Resultset).GetInt
, etc.
func main() {
// Open up our database connection.
db, err := sql.Open(“mysql”, “root:pass1@tcp(127.0.0.1:3306)/tuts”)
// if there is an error opening the connection, handle it
if err != nil {
log.Print(err.Error())
}
defer db.Close()
// Execute the query
results, err := db.Query("SELECT id, name FROM tags")
if err != nil {
panic(err.Error()) // proper error handling instead of panic in your app
}
for results.Next() {
var tag Tag
// for each row, scan the result into our tag composite object
err = results.Scan(&tag.ID, &tag.Name)
if err != nil {
panic(err.Error()) // proper error handling instead of panic in your app
}
// and then print out the tag's Name attribute
log.Printf(tag.Name)
}
This code is perfect upto now.
if I would like to use same “results” variable again. We don’t have any option.
We have to fire the same Query again and we have to assign “Second” Variable .
If we can do like this
resultset.first ; this is moving record pointer to first and we can use same result set again in the application
for results.Next() {
var tag Tag
// for each row, scan the result into our tag composite object
err = results.Scan(&tag.ID, &tag.Name)
if err != nil {
panic(err.Error()) // proper error handling instead of panic in your app
}
// and then print out the tag’s Name attribute
log.Printf(tag.Name)
}
}
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.