Go 插入整数时处理空值
我编写了一些代码,用于从.csv文件创建插入。 我在尝试插入空值字段时遇到问题。 在大多数情况下,my.csv中的字段都是整数,但有时需要为空。我知道我不能将“NULL”作为int传递,但在创建插入时如何适应这些NULL记录 在使用.csv Im的情况下,会出现一列:Go 插入整数时处理空值,go,Go,我编写了一些代码,用于从.csv文件创建插入。 我在尝试插入空值字段时遇到问题。 在大多数情况下,my.csv中的字段都是整数,但有时需要为空。我知道我不能将“NULL”作为int传递,但在创建插入时如何适应这些NULL记录 在使用.csv Im的情况下,会出现一列:CustomerID,该列可以是int,也可以是NULL 类似于sql.NullInt64的东西可以工作吗 以下是我正在编写的代码: func Unmarshal(reader *csv.Reader, v interface{})
CustomerID
,该列可以是int,也可以是NULL
类似于sql.NullInt64
的东西可以工作吗
以下是我正在编写的代码:
func Unmarshal(reader *csv.Reader, v interface{}) error {
record, err := reader.Read()
if err != nil {
return err
}
s := reflect.ValueOf(v).Elem()
if s.NumField() != len(record) {
return &FieldMismatch{s.NumField(), len(record)}
}
for i := 0; i < s.NumField(); i++ {
f := s.Field(i)
switch f.Type().Kind() {
case reflect.String:
f.SetString(record[i])
case reflect.Int:
ival, err := strconv.ParseInt(record[i], 10, f.Type().Bits())
if err != nil {
return err
}
f.SetInt(ival)
case reflect.Float64:
fval, err := strconv.ParseFloat(record[i], f.Type().Bits())
if err != nil {
return err
}
f.SetFloat(fval)
default:
return &UnsupportedType{f.Type().String()}
}
}
return nil
}
type FieldMismatch struct {
expected, found int
}
func (e *FieldMismatch) Error() string {
return "CSV line fields mismatch. Expected " + strconv.Itoa(e.expected) + " found " + strconv.Itoa(e.found)
}
type UnsupportedType struct {
Type string
}
func (e *UnsupportedType) Error() string {
return "Unsupported type: " + e.Type
}
func解组(reader*csv.reader,v接口{})错误{
记录,错误:=reader.Read()
如果错误!=零{
返回错误
}
s:=reflect.ValueOf(v).Elem()
如果s.NumField()!=len(记录){
返回和字段不匹配{s.NumField(),len(记录)}
}
对于i:=0;i
您是否尝试过使用sql.NullInt64
而不是sql.NullString
?对不起,我的意思是键入sql.NullInt64
,您建议我如何在reflect.ValueOf
中使用它?您可以为reflect.Interface
尝试另一条语句,然后调用记录[I].Interface()
并执行一个类型断言,以将其发送到sql.NullInt64
。只需确保添加一张零支票。