【Go】连接本地MySQL读取数据
时间:2021-07-01 10:21:17
帮助过:3人阅读
import (
"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:pwd@(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读取数据
标签:连接 nbsp oca star UNC map img code 请求