duanla1996 2015-08-11 15:46
浏览 98
已采纳

Go为什么将Postgresql数字和十进制列视为[] uint8?

I'm not sure if this is a bug in Go or just something I don't understand. I have the following:

package main

import (
  "database/sql"
  "log"
  "reflect"

  _ "github.com/lib/pq"
)

func main() {
  Db, err := sql.Open("postgres", "user=yoitsme password=openupitsme host=x.x.x.x dbname=mydb")
  if err != nil {
    log.Println(err)
  }
  rows, err := Db.Query("SELECT 1.3250::numeric, 8.548::decimal, 908.234::float, 1234::integer")
  defer rows.Close()
  for rows.Next() {
    var col1, col2, col3, col4 interface{}
    if err := rows.Scan(&col1, &col2, &col3, &col4); err != nil {
      log.Println(err)
    }
    log.Println(col1, reflect.TypeOf(col1))
    log.Println(col2, reflect.TypeOf(col2))
    log.Println(col3, reflect.TypeOf(col3))
    log.Println(col4, reflect.TypeOf(col4))
  }
  if err = rows.Err(); err != nil {
    log.Println(err)
  }

}

This prints:

2015/08/11 09:35:47 [49 46 51 50 53 48] []uint8
2015/08/11 09:35:47 [56 46 53 52 56] []uint8
2015/08/11 09:35:47 908.234 float64
2015/08/11 09:35:47 1234 int64

So, I get []uint8 (e.g. a string) for the first two columns that are actually numbers. The last 2 columns are as expected. According to Postgresql Numeric & Decimal types are part of the SQL standard. So, why doesn't Go follow the SQL standard in their database/sql package? Is it because Go doesn't have a builtin "Decimal" type? It seems wrong that the database/sql package turned a number into a string because of a shortcoming in the language....

  • 写回答

2条回答 默认 最新

  • dongshao9106 2015-08-11 15:57
    关注

    Because there is no better solution. (At least wasn't until Go 1.5's big.Float). What other alternatives are there?

    • Turn it into an integer. Obviously a bad solution since numerics can have a fractional part.

    • Turn it into a float64. This is evil. Especially if you're working with money (where types like numeric and decimal have the most usage).

    This particular database driver chooses instead to return a string containing the number - to let you decide, whether to lose some precision (by converting it into a float64 with strconv) or use a decimal/precise number library (like gmp or math/big).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集