【问题标题】:How to Handle Bit(1) type in Golang如何在 Golang 中处理 Bit(1) 类型
【发布时间】:2021-08-09 09:16:52
【问题描述】:

当数据库存储位(1)在列中输入并且我们从数据库中将该类型作为布尔类型时,我将得到以下错误。

couldn't convert "\x01" into type bool

那么,如何在 golang 中使用 bit(1) 类型以及如何从数据库中解析布尔数据。

【问题讨论】:

  • 我们从数据库中将该类型作为 bool 类型 BIT(1) 是 BINARY 数据类型。例如,您可以执行SELECT bit_column + 0, .. 而不是单个SELECT bit_column, ..,MySQL 会将二进制数据类型转换为数字。
  • 但我们不需要来自数据库的 tinyint(1) 或数值。我们需要 if 1 then true 并且 o 表示 false。我们需要一个布尔值。
  • 我们不需要来自数据库的 tinyint(1) 或数值 但是您可以将此数值转换为布尔值而无需描述问题,是吗?或者接收二进制值,并在golang中搜索正确的二进制->布尔变量数据类型转换,与MySQL无关。

标签: mysql go


【解决方案1】:

go-sql-driver/mysql issue 440 确实指出了相同的错误消息。

Gustavo Ibarra提议the workaround

type Transaction struct {
      IsSent           sql.NullBool   `gorm:"column:is_sent" json:"isSent,omitempty"`
}

与:

CREATE TABLE `transaction` (
  `is_sent` tinyint(1) unsigned DEFAULT '0',
...

它成功了,得到如下 JSON 响应:

"isSent": {
        "Bool": true,
        "Valid": true
    },

还有jmoiron/sqlx,其中Rayfen Windspear提出了一个类型BitBool MySQL类型BIT的Scanner/Valuer

// BitBool is an implementation of a bool for the MySQL type BIT(1).
// This type allows you to avoid wasting an entire byte for MySQL's boolean type TINYINT.
type BitBool bool

// Value implements the driver.Valuer interface,
// and turns the BitBool into a bitfield (BIT(1)) for MySQL storage.
func (b BitBool) Value() (driver.Value, error) {
    if b {
        return []byte{1}, nil
    } else {
        return []byte{0}, nil
    }
}

// Scan implements the sql.Scanner interface,
// and turns the bitfield incoming from MySQL into a BitBool
func (b *BitBool) Scan(src interface{}) error {
    v, ok := src.([]byte)
    if !ok {
        return errors.New("bad []byte type assertion")
    }
    *b = v[0] == 1
    return nil
}

【讨论】:

    猜你喜欢
    • 2011-02-11
    • 2021-12-08
    • 1970-01-01
    • 2017-08-28
    • 1970-01-01
    • 2016-01-15
    • 1970-01-01
    • 1970-01-01
    • 2023-01-27
    相关资源
    最近更新 更多