猿问

如何在 golang 中获取 MySQL 的 BIT(64)

我是新手,正在尝试从 MySQL 读取数据。架构:“id:INT(11),头部:TEXT,过滤器:BIT(64)”


我试图以常见的方式做到这一点:


type News struct {

    Id      int    `field:"id"`

    Head    string `field:"head"`

    Filter  uint64 `field:"filter"`

}

...

rows.Scan(&item.Id, &item.Head, &item.Filter)

并得到:


Scan error on column index 2, name "filter": converting NULL to uint64 is unsupported

我尝试了一些带有反射的示例,但没有结果。


我试过像这里一样制作自己的类型(真的不明白这个):


type BitMask uint64

func (bits *BitMask) Scan(src interface{}) error {

    str, ok := src.(string)

    if !ok {

        return fmt.Errorf("Unexpected type for BitMask: %T\n", src)

    }

    fmt.Println(str)

    //var v uint64 = 0

    //*bits = v // <- Also have error here

    return nil

}

并得到类似的错误:“BitMask 的意外类型:< nil>”


绝地无双
浏览 173回答 1
1回答

哈士奇WWW

我做出这个答案只是为了结束问题并总结结果。所以有2种方式:1 编写自己的类型:type BitMask sql.NullInt64func (bits *BitMask) Scan(src interface{}) error {&nbsp; if src == nil {&nbsp; &nbsp; bits.Int64 = 0&nbsp; &nbsp; bits.Valid = false&nbsp; &nbsp; return nil&nbsp; }&nbsp; buf, ok := src.([]byte)&nbsp; if !ok {&nbsp; &nbsp; return fmt.Errorf("Unexpected type for BitMask: %T\n", src)&nbsp; }&nbsp; if len(buf) != 8 {&nbsp; &nbsp; bits.Int64 = 0&nbsp; &nbsp; bits.Valid = false&nbsp; &nbsp; return errors.New("Size of bit filed is not 8 bytes\n")&nbsp; }&nbsp; bits.Int64 = 0&nbsp; for i := range buf {&nbsp; &nbsp; bits.Int64 *= 256&nbsp; &nbsp; bits.Int64 = int64(buf[i])&nbsp; }&nbsp; bits.Valid = true&nbsp; return nil}不要使用BIT(64),UNSIGNED BIGINT而是。因为没有优势,只有问题。(这就是我要做的)
随时随地看视频慕课网APP

相关分类

Go
我要回答