Mysql 如何处理Golang中的Bit(1)类型
当数据库在列中存储位(1)类型,并且我们从数据库中获取该类型作为bool类型时,我将得到下面的错误Mysql 如何处理Golang中的Bit(1)类型,mysql,go,Mysql,Go,当数据库在列中存储位(1)类型,并且我们从数据库中获取该类型作为bool类型时,我将得到下面的错误 无法将“\x01”转换为bool类型 所以,如何使用golang处理位(1)类型,以及如何从数据库解析布尔数据。确实指出了相同的错误消息 提议: 类型事务结构{ IsSent sql.NullBool`gorm:“列:已发送”json:“IsSent,省略为空”` } 与: 它成功了,得到了JSON响应,比如: “Isent”:{ “Bool”:没错, “有效”:真 }, 还有,其中为MyS
无法将“\x01”转换为bool类型
所以,如何使用golang处理位(1)类型,以及如何从数据库解析布尔数据。确实指出了相同的错误消息
提议:
类型事务结构{
IsSent sql.NullBool`gorm:“列:已发送”json:“IsSent,省略为空”`
}
与:
它成功了,得到了JSON响应,比如:
“Isent”:{
“Bool”:没错,
“有效”:真
},
还有,其中为MySQL类型BIT建议了一个类型BitBool
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
}
我们从数据库中获取该类型,因为布尔类型位(1)是二进制数据类型。例如,您可以执行SELECT bit_column+0,…
而不是单个SELECT bit_column,…
,MySQL将二进制数据类型转换为数字。但我们不需要数据库中的tinyint(1)或数字值。我们需要的是,如果1为真,那么o表示假。我们需要一个布尔值。我们不需要数据库中的tinyint(1)或数值,但您可以将此数值转换为布尔值,而无需说明问题,是吗?或者以二进制形式接收值,并在golang中搜索与MySQL无关的正确的二进制->布尔变量数据类型转换。
// 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
}