Created
August 16, 2016 09:12
-
-
Save derlin/71b89a3328e6b30e6ef5621a49a4c1a4 to your computer and use it in GitHub Desktop.
convert an sql.Rows to a map
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Convert an sql.Rows to a map | |
func SqlToMap(rows *sql.Rows) { | |
columns, err := rows.Columns() | |
scanArgs := make([]interface{}, len(columns)) | |
values := make([]interface{}, len(columns)) | |
results := make([]map[string]interface{}, 0) | |
for i := range values { | |
scanArgs[i] = &values[i] | |
} | |
for rows.Next() { | |
err = rows.Scan(scanArgs...) | |
if (err != nil) { | |
panic(err) | |
} | |
record := make(map[string]interface{}) | |
for i, col := range values { | |
if col != nil { | |
switch col.(type) { | |
case bool: | |
record[columns[i]] = col.(bool) | |
case int: | |
record[columns[i]] = col.(int) | |
case int64: | |
record[columns[i]] = col.(int64) | |
case float64: | |
record[columns[i]] = col.(float64) | |
case string: | |
record[columns[i]] = col.(string) | |
case time.Time: | |
record[columns[i]] = col.(time.Time) | |
case []byte: | |
record[columns[i]] = string(col.([]byte)) | |
default: | |
record[columns[i]] = col | |
} | |
} | |
} | |
results = append(results, record) | |
} | |
s, _ := json.Marshal(results) | |
fmt.Println(string(s)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment