dimanche 31 mai 2020

golang get value from nested interface

I have a small problem while trying to dynamically read string from my db using odbc and no ORM.

maybe it's worth mentioning that with another SQL server driver I receive the data as string and not []uint8 which solving my problem).

I'm using the following code to scan a row into slice array:

func createEmptyResultSet(numOfCols int) []interface{} {
res := make([]interface{}, numOfCols)
for col := 0; col < numOfCols; col++ {
    var i interface{}
    res[col] = &i
}
return res

} and the actual scan:

func rowsToStringInterfaceMapSlice(rows *sql.Rows, cols []string) ([]map[string]interface{}, error) {
    var err error
    rowsRes := make([]map[string]interface{}, 0)
    numOfCols := len(cols)
    for rows.Next() {
        row := make(map[string]interface{}, numOfCols)
        values := createEmptyResultSet( numOfCols)
        if rows.Scan(values...); err != nil {
            return nil, err
        }
        rowsRes = append(rowsRes, row)
    }
    return rowsRes, nil
}

I'm trying to access the following slice:

enter image description here

using few versions of the following code:

  for i := range values {
//also tried multiple get value
                t := reflect.TypeOf(values[i])
                if t.Kind() == reflect.Slice {
                    row[cols[i]] = interfaceSliceToString(values[i])
                } else {
                    row[cols[i]] = values[i]
                }
            }

but nothing seems to work. any suggestions?





Aucun commentaire:

Enregistrer un commentaire