N
N
Newmo2019-05-31 10:13:08
go
Newmo, 2019-05-31 10:13:08

How to translate the result of type sql.Result into a string?

Get value from database:

maxvalue, err := db.Exec("SELECT MAX(points) FROM items")

How to translate the result into a string to assign it to a variable?
Now naturally I get the following error when assigning:
cannot use maxvalue (type sql.Result) as type string in assignment

Maybe I'm doing something wrong? I need to get the maximum value in the column and pass it in a variable to the template in the Data structure:
t.ExecuteTemplate(w, "single", Data)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Pavlyuk, 2019-05-31
@Newmo

You are not using that function. Exec is needed to execute a query that returns nothing.
You need Query
And it's better to put it all in a separate function in order to use defer

func GetMaxPoints(db *sql.DB) (int64, error) {
  rows, err := db.Query(`SELECT MAX(points) FROM items`)
  if err != nil {
    return 0, err
  }
  defer rows.Close()
  rows.Next()
  var maxPoints int64
  err = rows.Scan(&maxPoints)
  return maxPoints, err
}

O
O. J, 2019-05-31
@OrlovEvgeny

resultStr := maxvalue.(string)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question