GoLang 基础知识 mysql相关

将 sql 建表语句转为 struct

1
https://sql2struct.js.org/

将 rows 转为 Map

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// 把rows转换成记录
func makeRowsMap(rows *sql.Rows) []map[string]interface{} {
colTypes, _ := rows.ColumnTypes() // 列信息
var rowParam = make([]interface{}, len(colTypes)) // 传入到 rows.Scan 的参数 数组
var rowValue = make([]interface{}, len(colTypes)) // 接收数据一行列的数组

for i, colType := range colTypes {
rowValue[i] = reflect.New(colType.ScanType()) // 跟据数据库参数类型,创建默认值 和类型
rowParam[i] = reflect.ValueOf(&rowValue[i]).Interface() // 跟据接收的数据的类型反射出值的地址
//logging.Debugf("%s:%s,%s",colType.Name(),colType.ScanType().String(),colType.DatabaseTypeName()) // 字段明称:类型,数据库类型
}

var arrays []map[string]interface{} = make([]map[string]interface{},0)
for rows.Next() {
rows.Scan(rowParam...)
record := make(map[string]interface{})
for i, colType := range colTypes {
if colType.ScanType().String() == "time.Time" { // 日期要格式化下
record[colType.Name()] = rowValue[i].(time.Time).Format("2006-01-02 15:04:05")
}else if colType.DatabaseTypeName() == "NUMERIC" { // number 居然是 interface{} 操蛋[]uint8的数组,后来发现转成string 后在转float
record[colType.Name()],_ = strconv.ParseFloat(string(rowValue[i].([]byte)),64)
}else{
record[colType.Name()] = rowValue[i]
}

//logging.Debugf("%s(%s-%s):%s",colType.Name(),colType.ScanType().String(),colType.DatabaseTypeName(),rowValue[i])

}
arrays = append(arrays, record)
}
return arrays
}

func byteToFloat64(bytes []byte) float64 {
bits := binary.LittleEndian.Uint64(bytes)

return math.Float64frombits(bits)
}