修复null值问题,添加安全版和非安全版接口

This commit is contained in:
aozhiwei 2023-12-11 17:48:52 +08:00
parent 64cce9a691
commit 0431c236bd
2 changed files with 77 additions and 14 deletions

View File

@ -2,6 +2,7 @@ package f5
import (
"database/sql"
"q5"
)
type DataSet struct {
@ -15,10 +16,13 @@ func (this *DataSet) Next() bool {
this.GetColumns()
this.values = []interface{}{}
for i := 0; i < len(this.columns); i++ {
str := ""
str := sql.NullString{}
this.values = append(this.values, &str)
}
this.rows.Scan(this.values...)
err := this.rows.Scan(this.values...)
if err != nil {
panic("DataSet Next error:" + err.Error())
}
return ret
}
@ -32,27 +36,86 @@ func (this *DataSet) GetColumns() []string {
return this.columns
}
func (this *DataSet) GetValues() *[]*string {
values := []*string{}
/*
安全版:nil值视为""
*/
func (this *DataSet) GetValues() *[]string {
values := []string{}
for _, val := range this.values {
values = append(values, val.(*string))
raw_val := val.(*sql.NullString)
if raw_val.Valid {
values = append(values, raw_val.String)
} else {
values = append(values, *q5.NewEmptyStrPtr())
}
}
return &values
}
func (this *DataSet) GetByName(name string) *string {
this.GetColumns()
for i := 0; i < len(this.columns); i++ {
if this.columns[i] == name {
return this.GetByIndex(int32(i))
/*
安全版:nil值视为""
*/
func (this *DataSet) GetByName(name string) string {
val := this.GetRawValueByName(name)
if val == nil {
return ""
} else {
return *val
}
}
/*
安全版:nil值视为""
*/
func (this *DataSet) GetByIndex(index int32) string {
val := this.GetRawValueByIndex(index)
if val == nil {
return ""
} else {
return *val
}
}
/*
!!!原始版: 调用方应处理值为nil的情况
*/
func (this *DataSet) GetRawValues() *[]string {
values := []*string{}
for _, val := range this.values {
raw_val := val.(*sql.NullString)
if raw_val.Valid {
values = append(values, &raw_val.String)
} else {
values = append(values, nil)
}
}
return nil
}
func (this *DataSet) GetByIndex(index int32) *string {
/*
!!!原始版: 调用方应处理值为nil的情况
*/
func (this *DataSet) GetRawValueByName(name string) *string {
this.GetColumns()
return this.values[index].(*string)
for i := 0; i < len(this.columns); i++ {
if this.columns[i] == name {
return this.GetRawValueByIndex(int32(i))
}
}
return nil
}
/*
!!!原始版: 调用方应处理值为nil的情况
*/
func (this *DataSet) GetRawValueByIndex(index int32) *string {
this.GetColumns()
sql_val := this.values[index].(*sql.NullString)
if sql_val.Valid {
return &sql_val.String
} else {
return nil
}
}
func NewDataSet(rows *sql.Rows) *DataSet {

View File

@ -238,8 +238,8 @@ func (this *dbPool) PageQuery(
return
}
if rows != nil && rows.Next() {
pagination.Total = q5.ToInt32(*rows.GetByIndex(0))
pagination.TotalPages = int32(math.Ceil(q5.ToFloat64(*rows.GetByIndex(0)) /
pagination.Total = q5.ToInt32(rows.GetByIndex(0))
pagination.TotalPages = int32(math.Ceil(q5.ToFloat64(rows.GetByIndex(0)) /
float64(pagination.PerPage)))
}
start := pagination.PerPage * (pagination.CurrentPage - 1)