In my golang app i need to do SQL query to MySQL to get single row and put result in a map[string]string keys are column names.
But i don't know what will be columns. Query is like
SELECT * FROM mytable
I use "database/sql" .
I found only Scan function
db.QueryRow("SELECT * FROM mytable").Scan(&var1, &var2,...)
but this doesn't work for my condition. I don't know how many variables will be there. And also I need column names.
Is it possible to do with database/sql ?
Update. I found how to solve part of this problem. How to get column names from a result set.
rows, err := db.Query(sqlcommand)
cols, err := rows.Columns()
So, i can use to make keys for a map. But i still don't know how to get values. Because, values can have different type.
data = make(map[string]string)
if rows.Next() {
columns := make([]interface{}, len(cols))
columnPointers := make([]interface{}, len(cols))
for i, _ := range columns {
columnPointers[i] = &columns[i]
}
err = rows.Scan(columnPointers...)
for i, colName := range cols {
// value is in columns[i] of interface type.
// How to extract it from here?
// ....
data[colName] = val
}
}
P.S. This question is not duplicate of "Get table column names in mysql? ". I wanted to get columns of returned data set, not just a table.