1. 安装 Mysql
- 本地数据库导入(windows本地安装mysql5.7)
安装完成以后需要配置环境变量
2. 安装 Git
-
添加环境变量
-
在Go工作目录下安装go的mysql连接驱动
go get github.com/go-sql-driver/mysql
go get github.com/jmoiron/sqlx
安装需要等待时间较长,如果网络不稳定,需要多试几次
安装失败需要把下面的参数进行更改:
3. 配置 Navicat
3. 对接数据库操作
插入数据
package main
import (
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
)
type Persion struct {
UserId int `db:"user_id"`
Username string `db:"username"`
Sex string `db:"sex"`
Email string `db:"email"`
}
//数据库结构体
var Db *sqlx.DB
func init() {
//连接数据库,"用户名:密码@协议(地址:端口)/数据库名称"
database, err := sqlx.Open("mysql", "root:abc123@tcp(127.0.0.1:3306)/school")
if err != nil {
fmt.Println("打开数据库失败,err:", err)
return
}
//初始化数据库
Db = database
}
func main() {
r, err := Db.Exec("insert into persion (username,sex,email) value(?,?,?)", "stu01", "boy", "stu01@qq.com")
if err != nil {
fmt.Println("修改失败,err:", err)
return
}
id, err := r.LastInsertId()
if err != nil {
fmt.Println("修改失败,err:", err)
return
}
fmt.Printf("修改成功,修改了第%d个数据", id)
}
//执行结果如下
修改成功,修改了第5个数据
查询数据
package main
import (
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
)
type Persion struct {
UserId int `db:"user_id"`
Username string `db:"username"`
Sex string `db:"sex"`
Email string `db:"email"`
}
//数据库结构体
var Db *sqlx.DB
func init() {
//连接数据库,"用户名:密码@协议(地址:端口)/数据库名称"
database, err := sqlx.Open("mysql", "root:abc123@tcp(127.0.0.1:3306)/school")
if err != nil {
fmt.Println("打开数据库失败,err:", err)
return
}
//初始化数据库
Db = database
}
func main() {
var persion []Persion
err := Db.Select(&persion, "select user_id,username,sex,email from persion where user_id=?", 1)
if err != nil {
fmt.Println("读取失败,err", err)
return
}
fmt.Println("查询成功:", persion)
}
//输出结果如下
查询成功: [{1 zhangsan 男 123@163.com}]
在 web 页面展示数据
package main
import (
"fmt"
"io"
"log"
"net/http"
"strconv"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
)
const form = `<html>
<head></head>
<body>
<form action="#" method="post" name="bar">
<input type="text" name="in"/>
<input type="submit" value="submit"/>
</form>
</body>
</html>`
type Person struct {
UserID int `db:"user_id"`
UserName string `db:"username"`
Sex string `db:"sex"`
Email string `db:"email"`
}
//数据库结构体
var DB *sqlx.DB
func init() {
//("连接数据库","用户名:密码@协议(地址:端口)/数据库名")
database, err := sqlx.Open("mysql", "root:abc123@tcp(127.0.0.1:3306)/school")
if err != nil {
fmt.Println("打开数据库失败,err", err)
return
}
DB = database
}
//HTTP服务端配置
//业务请求响应处理
// func hello(res http.ResponseWriter, req *http.Request) {
// fmt.Println("hello")
// fmt.Fprintln(res, "<h1>welcome<h1>")
// }
//form表单处理
func formServer(res http.ResponseWriter, req *http.Request) {
//头部申明
res.Header().Set("Content-Type", "text/html")
//提交类型判断
switch req.Method {
case "GET":
io.WriteString(res, form)
case "POST":
req.ParseForm()
//读取第一个框体内容给response做页面回应
id, err := strconv.Atoi(req.Form["in"][0])
if err != nil {
fmt.Println("数据类型转换失败, err:", err)
return
}
//定义获取数据的切片,用来装载查询结果
var person []Person
err = DB.Select(&person, "select user_id,username,sex,email from person where user_id=?", id)
if err != nil {
fmt.Println("查询失败,err:", err)
return
}
//获取查询结果
for _, v := range person {
io.WriteString(res, strconv.Itoa(v.UserID))
io.WriteString(res, "\n")
io.WriteString(res, v.UserName)
io.WriteString(res, "\n")
io.WriteString(res, v.Sex)
io.WriteString(res, "\n")
io.WriteString(res, v.Email)
io.WriteString(res, "\n")
}
}
}
func main() {
//路由到指定站点位置跳转相关函数处理
http.HandleFunc("/mysql", logPanic(formServer))
err := http.ListenAndServe("127.0.0.1:8088", nil)
if err != nil {
fmt.Println("启动监听失败,err:", err)
return
}
}
//宕机恢复recover,注意使用在defer中
func logPanic(handle http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
defer func() {
if x := recover(); x != nil {
log.Printf("[%v]caught panic:%v", r.RemoteAddr, x)
}
}()
handle(w, r)
}
}
web 页面进行数据的修改/更新
package main
import (
"fmt"
"io"
"net/http"
"strconv"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
)
//定义页面表单HTML
const form = `<html><body><form action="#" method="post" name="bar">
<p>ID<input type="text" name="in"/></p>
<p>UserName<input type="text" name="in"/></p>
<input type="submit" value="Submit"/>
</form></body></html>`
type Person struct {
UserId int `db:"user_id"`
UserName string `db:"username"`
Sex string `db:"sex"`
Email string `db:"email"`
}
//数据库结构体
var DB *sqlx.DB
func init() {
//连接数据库,"用户名:密码@协议(地址:端口)/数据库名"
database, err := sqlx.Open("mysql", "root:abc123@tcp(127.0.0.1:3306)/school")
if err != nil {
fmt.Println("打开数据库失败,err:", err)
return
}
DB = database
}
//form表单处理
func formServer(res http.ResponseWriter, req *http.Request) {
//头部申明
res.Header().Set("Content-Type", "text/html")
//提交类型判断
switch req.Method {
case "GET":
io.WriteString(res, form)
case "POST":
req.ParseForm()
//获取from框体中的数据,转换成int类型
id, err := strconv.Atoi(req.Form["in"][0])
if err != nil {
fmt.Println("数据类型转换失败,err:", err)
return
}
rename := req.Form["in"][1]
//更新数据
_, err = DB.Exec("update person set username=? where user_id=?", rename, id)
if err != nil {
fmt.Println("更新数据失败,err:", err)
return
} else {
io.WriteString(res, "update succ")
}
}
}
func main() {
http.HandleFunc("/mysql", formServer)
if err := http.ListenAndServe("127.0.0.1:8088", nil); err != nil {
fmt.Println("启动监听失败,err:", err)
return
}
}
在 web 页面中对数据进行删除
package main
import (
"fmt"
"io"
"net/http"
"strconv"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
)
//定义页面表单HTML
const form = `<html><body><form action="#" method="post" name="bar">
ID<input type="text" name="in"/>
<input type="submit" value="Submit"/>
</form></body></html>`
type Person struct {
UserId int `db:"user_id"`
UserName string `db:"username"`
Sex string `db:"sex"`
Email string `db:"email"`
}
//数据库结构体
var DB *sqlx.DB
func init() {
//连接数据库,"用户名:密码@协议(地址:端口)/数据库名"
database, err := sqlx.Open("mysql", "root:abc123@tcp(127.0.0.1:3306)/school")
if err != nil {
fmt.Println("打开数据库失败,err:", err)
return
}
DB = database
}
//form表单处理
func formServer(res http.ResponseWriter, req *http.Request) {
//头部申明
res.Header().Set("Content-Type", "text/html")
//提交类型判断
switch req.Method {
case "GET":
io.WriteString(res, form)
case "POST":
req.ParseForm()
//获取from框体中的数据,转换成int类型
id, err := strconv.Atoi(req.Form["in"][0])
if err != nil {
fmt.Println("数据类型转换失败,err:", err)
return
}
//删除数据
_, err = DB.Exec("delete from person where user_id=?", id)
if err != nil {
fmt.Println("del data,err:", err)
return
} else {
io.WriteString(res, "del succ")
}
}
}
func main() {
http.HandleFunc("/mysql", formServer)
if err := http.ListenAndServe("127.0.0.1:8088", nil); err != nil {
fmt.Println("启动监听失败,err:", err)
return
}
}