dtkwt62022 2014-01-22 21:22
浏览 53
已采纳

扫描到无效类型时,Sqlx不引发错误

I am using sqlx in Go, which is very helpful, but it does not seem to throw errors when I use struct scan and the types of the struct don't match the sql types. For example here I set up a database to have a name (string) and age(int):

+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| name  | varchar(255) | NO   |     | NULL    |       |
| age   | int(11)      | NO   |     | NULL    |       |
+-------+--------------+------+-----+---------+-------+
+------+-----+
| name | age |
+------+-----+
| bob  |  10 |
+------+-----+

I then use sqlx to read out the values into a struct, but the struct has the wrong types.

package main

import (
  "log"
  "github.com/jmoiron/sqlx"
  _ "github.com/go-sql-driver/mysql"
)

// in database name is a string and age is an int

type Person struct{
  Name int
  Age string
}

func main() {
  sqlSession, err := sqlx.Open("mysql", "root:@(localhost:3306)/dashboard?parseTime=true")
  if err != nil {
    log.Panic(err)
  }
  err = sqlSession.Ping()
  if err != nil {
    log.Panic(err)
  }
  query := "SELECT * FROM test"
  rows, errSql := sqlSession.Queryx(query)
  if errSql != nil {
    log.Panic(errSql)
  }
  for rows.Next() {
    var p Person
    errScan := rows.StructScan(&p)
    if errScan != nil {
      log.Panic(errScan)
    }
    log.Println("Person:", p)
  }
}

So instead of giving me an error, it has zeroed out values. Person: {0 }

Has anyone else run into this problem? Does any one else think this is a bug? I think it should give me an error when I try to scan into an invalid type.

  • 写回答

1条回答 默认 最新

  • dongmanni6916 2014-01-23 14:43
    关注

    I suspect that is a side-effect of deciding not to return errors when it can't find a place to put the returned value. One reason you may not want to return an error is if you do a "select *", then even if your struct has all columns, you will not be able to add new columns without the code immediately beginning to return errors.

    One could argue that if all the query columns were unused, then it should return an error. Probably opening an issue with the project would be the way to go.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址