f5/dataset.go
aozhiwei 30a7e2a6ea 1
2023-12-11 17:56:28 +08:00

129 lines
2.3 KiB
Go

package f5
import (
"database/sql"
"q5"
)
type DataSet struct {
rows *sql.Rows
columns []string
values []interface{}
}
func (this *DataSet) Next() bool {
ret := this.rows.Next()
if !ret {
return ret
}
this.GetColumns()
this.values = []interface{}{}
for i := 0; i < len(this.columns); i++ {
str := sql.NullString{}
this.values = append(this.values, &str)
}
err := this.rows.Scan(this.values...)
if err != nil {
panic("DataSet Next error:" + err.Error())
}
return ret
}
func (this *DataSet) GetColumns() []string {
if len(this.columns) <= 0 {
columns, err := this.rows.Columns()
if err == nil {
this.columns = columns
}
}
return this.columns
}
/*
安全版:nil值视为""
*/
func (this *DataSet) GetValues() *[]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, *q5.NewEmptyStrPtr())
}
}
return &values
}
/*
安全版: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
}
/*
!!!原始版: 调用方应处理值为nil的情况
*/
func (this *DataSet) GetRawValueByName(name string) *string {
this.GetColumns()
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 {
dataSet := new(DataSet)
dataSet.rows = rows
return dataSet
}