Skip to content
Advertisement

Is there a way to get the Type for a Column using package database/sql in golang?

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

  1. make an array of interface{} the size of Column(),
  2. then for each column determine it’s type,
  3. then fill the array with a pointer to that type,
  4. 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());
    }
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement