douhe5092 2013-07-25 16:00
浏览 245

有没有一种方法可以在golang中使用包database / sql获取列的类型?

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.

  • 写回答

1条回答 默认 最新

  • dounaidu0204 2014-06-03 14:50
    关注

    Using database/sql? No (as far as I know).

    But you can use this code for arbitrary queries. And json.Marshall() from the json package will use reflection to determine the right way to print a value, so you could have a structure like this:

    type Column struct {
        ColumnName  string
        ColumnValue interface{}
        ColumnType  string
    }
    

    And then use reflect.TypeOf(someVariable).String() to get the type for ColumnType.

    评论

报告相同问题?

悬赏问题

  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 关于无人驾驶的航向角
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了