【Go】连接本地MySQL读取数据[数据库教程]
如题。对Go的网页请求参数有一些了解,从头开始呗。
数据库的goods表
package mainimport ("fmt""log"
"net/http"
"strconv"
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
func AddHandler(w http.ResponseWriter, r *http.Request) {
vars := r.URL.Query()
a := vars.Get("para")
b := vars.Get("para2")
inta, _ := strconv.Atoi(a)
intb, _ := strconv.Atoi(b)
fmt.Println(r.Method, r.URL, r.Host, vars)
fmt.Println(r.Proto)
fmt.Fprintln(w, inta+intb)
}
type Good struct {
Name string
Count string
Price string
}
func CheckErr(err error, paras ...string) {
if err != nil {
for _, val := range paras {
log.Println(val)
}
log.Fatal(err)
}
}
func main() {
db, _ := sql.Open("mysql", "root:[email protected](127.0.0.1:3306)/mysql")
defer db.Close()
err := db.Ping()
CheckErr(err, "SQLErr")
log.Println("Success")
query := "select * from goods"
rows, _ := db.Query(query)
var id, name, count, price string
var nameCount map[string] int
nameCount = make(map[string]int)
for rows.Next() {
rows.Scan(&id, &name, &count, &price)
_count, err := strconv.Atoi(count)
CheckErr(err, id, name, count, price)
_, ok := nameCount[name]
if (ok) {
nameCount[name] += _count
} else {
nameCount[name] = _count
}
}
for k, v := range nameCount {
fmt.Println(k, v)
}
http.HandleFunc("/", AddHandler)
log.Println("Listen : 15233")
err = http.ListenAndServe("0.0.0.0:15233", nil)
CheckErr(err, "ListenErr")
fmt.Println("Start open")
}
View Code
运行命令: go run test.go
浏览器地址输入 localhost:15233。
【Go】连接本地MySQL读取数据
原文:https://www.cnblogs.com/zhouys96/p/12793268.html
以上是 【Go】连接本地MySQL读取数据[数据库教程] 的全部内容, 来源链接: utcz.com/z/533367.html