for rows.Next() {
var data string
err = rows.Scan(&data)
if err != nil {
panic(err.Error())
}
results = append(results, data)
}
类似这种 Scan 里面的个数和select的个数都要一致
请问有没有性能高的 且 直接返回数组或者map的方法??
看这问题挂了好几天了,搜了下go官方源码,里面相关`xxx_test.go`里面就有你想要的东西,我这里搞了个通用查询,查询结果你需要自己想办法处理一下。
```go
package main
import (
"database/sql"
"flag"
"fmt"
"reflect"
_ "github.com/go-sql-driver/mysql"
)
func main() {
dns := flag.String("m", "user:pass@tcp(ip:port)/db?charset=utf8&parseTime=true&loc=Local", "")
flag.Parse()
err := mysql(*dns)
if err != nil {
panic(err)
}
}
func mysql(dsn string) error {
db, err := sql.Open("mysql", dsn)
if err != nil {
return err
}
defer db.Close()
rows, err := db.Query("select * from test limit 5")
if err != nil {
return err
}
defer rows.Close()
cts, err := rows.ColumnTypes()
if err != nil {
return err
}
var (
ctLen = len(cts)
types = make([]reflect.Type, ctLen)
names = make([]string, ctLen)
)
for i, tp := range cts {
st := tp.ScanType()
if st != nil {
types[i] = st
names[i] = tp.Name()
}
}
var resp []map[string]any
for rows.Next() {
values := make([]any, ctLen)
for i := range values {
values[i] = reflect.New(types[i]).Interface()
}
err = rows.Scan(values...)
if err != nil {
return err
}
tmp := make(map[string]any, ctLen)
for i, v := range values {
// 注意列可以为NULL的值会解析为sql.Nullxxx
// []byte和string会被解析为sql.RawBytes
tmp[names[i]] = reflect.ValueOf(v).Elem().Interface()
}
resp = append(resp, tmp)
}
fmt.Println(resp)
return nil
}
```
#15