go-mysql

时间:2022-03-10 17:39:39

 1 package main
 2 
 3 import (
 4     "log"
 5     _ "github.com/go-sql-driver/mysql" 
 6     "github.com/jmoiron/sqlx" // 驱动
 7 )
 8 
 9 type Class struct {
10     Id int64
11     Name string
12     Desc string
13 }
14 
15 func main() {
16     // 建立连接
17     db, err := sqlx.Open(`mysql`, `root:[email protected](127.0.0.1:3306)/test?charset=utf8&parseTime=true`)
18     log.Println(db, err)
19     // 查询
20     // Get查询一个
21     // Select一个集合
22     // 非查询
23     // db.Exec() //执行insert update delete
24     
25     mode := Class{}
26     log.Println("---", mode)
27     db.Get(&mode, "select * from student")
28     log.Println("---", mode)
29 }

go-mysql

 

 go-mysql

 

 

 1 package main
 2 
 3 import (
 4     "net/http"
 5     "log"
 6     "encoding/json"
 7     _ "github.com/go-sql-driver/mysql" 
 8     "github.com/jmoiron/sqlx" // 驱动
 9 )
10 
11 type Class struct {
12     Id int64
13     Name string
14     Desc string
15 }
16 
17 func index(w http.ResponseWriter, r *http.Request) {
18     // 建立连接
19     db, err := sqlx.Open(`mysql`, `root:[email protected](127.0.0.1:3306)/test?charset=utf8&parseTime=true`)
20     log.Println(db, err)
21     // 查询
22     // Get查询一个
23     // Select一个集合
24     // 非查询
25     // db.Exec() //执行insert update delete
26     
27     mode := Class{}
28     log.Println("---", mode)
29     db.Get(&mode, "select * from student")
30     log.Println("---", mode)
31     // 序列化
32     jsonbytes, _ := json.Marshal(mode)
33     w.Write(jsonbytes)
34 }
35 
36 func main() {
37     // 路由
38     // 访问前面的路径
39     http.HandleFunc("/", index)
40     http.ListenAndServe(":8080", nil)
41 }

go-mysql

 

 go-mysql