有没有办法在golang中使用database/sql包获取列的类型?

huangapple go评论122阅读模式
英文:

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

问题

基本上,不事先知道查询结果结构的情况下,我想查询数据库并返回一个类似这样的结构(json-y)

// 行
[
// 行1
[
{ ColumnName: "id", Value: 1, Type: int },
{ ColumnName: "name", Value: "batman", Type: string },
...
],

// 行2
[
{ ColumnName: "id", Value: 2, Type: int },
{ ColumnName: "name", Value: "superman", Type: string },
...
]
]

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

我怀疑我想要做的是:

  1. 创建一个与列数量相同的interface{}数组,
  2. 然后对每一列确定其类型,
  3. 然后用指向该类型的指针填充数组,
  4. 然后将数组传递给Scan()函数。

这有点像sqlx中的这个代码示例,但不需要事先知道数据将填充的结构。

英文:

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)

  1. // Rows
  2. [
  3. // Row 1
  4. [
  5. { ColumnName: "id", Value: 1, Type: int },
  6. { ColumnName: "name", Value: "batman", Type: string },
  7. ...
  8. ],
  9. // Row 2
  10. [
  11. { ColumnName: "id", Value: 2, Type: int },
  12. { ColumnName: "name", Value: "superman", Type: string },
  13. ...
  14. ]
  15. ]

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

得分: 6

你应该可以这样做:

  1. func printRows(rows *sql.Rows){
  2. colTypes, err := rows.ColumnTypes()
  3. for _,s := range colTypes {
  4. log.Println("cols type:", s.DatabaseTypeName());
  5. }
  6. }
英文:

You should be able to do it this way:

  1. func printRows(rows *sql.Rows){
  2. colTypes, err := rows.ColumnTypes()
  3. for _,s := range colTypes {
  4. log.Println("cols type:", s.DatabaseTypeName());
  5. }
  6. }

答案2

得分: 0

使用database/sql吗?不是(据我所知)。

但是你可以使用这段代码来进行任意查询。而json包中的json.Marshall()函数会使用反射来确定正确的打印值的方式,所以你可以有一个像这样的结构:

  1. type Column struct {
  2. ColumnName string
  3. ColumnValue interface{}
  4. ColumnType string
  5. }

然后使用reflect.TypeOf(someVariable).String()来获取ColumnType的类型。

英文:

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:

  1. type Column struct {
  2. ColumnName string
  3. ColumnValue interface{}
  4. ColumnType string
  5. }

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

huangapple
  • 本文由 发表于 2013年7月26日 00:00:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/17863113.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定