Basically, without knowing before hand what the resulting structure of a query might be, I’d like to query the database, and return a structure like this (json-y)
// Rows [ // Row 1 [ { ColumnName: "id", Value: 1, Type: int }, { ColumnName: "name", Value: "batman", Type: string }, ... ], // Row 2 [ { ColumnName: "id", Value: 2, Type: int }, { ColumnName: "name", Value: "superman", Type: string }, ... ] ]
Is there a way to get the Type for a Column using package database/sql in golang?
I’m suspecting that what I want to do is
- make an array of interface{} the size of Column(),
- then for each column determine it’s type,
- then fill the array with a pointer to that type,
- and then pass the array to Scan()
Which is a little like this code example from sqlx, but without first knowing the Struct that the data would be populating.
Advertisement
Answer
You should be able to do it this way:
func printRows(rows *sql.Rows){ colTypes, err := rows.ColumnTypes() for _,s := range colTypes { log.Println("cols type:", s.DatabaseTypeName()); } }