最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
golang mysql查询返回不定字段
时间:2022-06-25 04:43:27 编辑:袖梨 来源:一聚教程网
golang mysql查询返回不定字段实现如下:
首先通过func (rs *Rows) Columns() ([]string, error)获取查询字段的slice,然后构造slice,将每次scan出来的值放进去,最后返回查询结果的map slice。
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func main() {
conn, err := sql.Open("mysql", "root:psw@tcp(localhost:3306)/test?charset=utf8")
if err != nil {
fmt.Println("mysql connect error")
return
}
defer conn.Close()
rows, err := conn.Query("select * from user")
if err != nil {
fmt.Println("mysql query error", err.Error())
}
defer rows.Close()
columns, err := rows.Columns()
values := make([]sql.RawBytes, len(columns))
scans := make([]interface{}, len(columns))
for i := range values {
scans[i] = &values[i]
}
var result []map[string]string
for rows.Next() {
_ = rows.Scan(scans...)
each := make(map[string]string)
for i, col := range values {
each[columns[i]] = string(col)
}
result = append(result, each)
}
fmt.Println(result)
}
同理查询单条也可以这样操作:
func main() {
conn, err := sql.Open("mysql", "root:psw@tcp(localhost:3306)/test?charset=utf8")
if err != nil {
fmt.Println("mysql connect error", err.Error())
return
}
defer conn.Close()
columns := []string{"id", "name"}
id := 1
sql := fmt.Sprintf("select %s from user where id=%d", strings.Join(columns, ", "), id)
row := conn.QueryRow(sql)
values := make([][]byte, len(columns))
scans := make([]interface{}, len(columns))
for i := range values {
scans[i] = &values[i]
}
if err := row.Scan(scans...); err != nil {
fmt.Println("scan error", err.Error())
return
}
var result = make(map[string]string)
for key, val := range values {
result[columns[key]] = string(val)
}
fmt.Println(result)
}