golang如何把struct绑定到原生SQL查询

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
package main

type Power struct {
Ts time.Time
Current float32
Voltage int
Phase float32
}

func main() {
var taosUri = "root:taosdata@tcp(localhost:6030)/power"
taos, err := sql.Open("taosSql", taosUri)
if err != nil {
fmt.Println("failed to connect TDengine, err:", err)
return
}
sql := "select * from d1001"
rows, err := taos.Query(sql)
defer rows.Close()
for rows.Next() {
power := Power{}
s := reflect.ValueOf(&power).Elem()
numCols := s.NumField()
columns := make([]interface{}, numCols)
for i := 0; i < numCols; i++ {
field := s.Field(i)
columns[i] = field.Addr().Interface()
}
err := rows.Scan(columns...)
if err != nil {
fmt.Println(err)
}
log.Printf("采集时间:%v, 当前值:%v, 电压:%d", power.Ts, power.Current, power.Voltage)
}
}

本文采用CC-BY-SA-3.0协议,转载请注明出处
Author: iPenge