GO语言学习之输出Mysql查询结果

  • A+
所属分类:golang mysql
package main

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"log"
)

func checkErr(err error) {
	if err != nil {
		log.Fatal(err)
	}
}

func main() {
	db, err := sql.Open("mysql", "root:001208@/go?charset=utf8")
	checkErr(err)
	// stmt, err := db.Prepare("INSERT INTO user (name, age, email) VALUES ('张三', 27, '9999999999@qq.com')")
	// checkErr(err)
	// res, err := stmt.Exec()
	// checkErr(err)
	rows, err := db.Query("SELECT * FROM user")
	checkErr(err)
	res, err := parseResult(rows)
	checkErr(err)
	for k, v := range res {
		fmt.Println(k, v)
	}
}

func parseResult(query *sql.Rows) (map[int]map[string]string, error) {
	columns, _ := query.Columns()
	values := make([][]byte, len(columns))
	scans := make([]interface{}, len(columns))
	results := make(map[int]map[string]string)
	for i := range scans {
		scans[i] = &values[i]
	}
	i := 0
	for query.Next() {
		if err := query.Scan(scans...); err != nil {
			return nil, err
		}
		row := make(map[string]string)
		for k, v := range values {
			key := columns[k]
			row[key] = string(v)
		}
		results[i] = row
		i++
	}
	return results, nil
}

输出结果

GO语言学习之输出Mysql查询结果

weinxin
我的微信
欢迎来撩!!

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: