安装驱动
go get -u github.com/go-sql-driver/mysql
初始化模块
go mod init m
执行go mod tidy
go mod tidy
连接数据库
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
var db *sql.DB
func initDB() (err error) {
dsn := "root:admin123@tcp(localhost:3306)/jiakao?charset=utf8mb4&parseTime=true"
db, err = sql.Open("mysql", dsn)
if err != nil {
return err
}
err = db.Ping()
if err != nil {
return err
}
return nil
}
func main() {
err := initDB()
if err != nil {
fmt.Printf("err: %v\n", err)
} else {
fmt.Println("连接成功")
}
}
插入操作
...
func insert(name string, value string, intro string) {
s := "insert into dict_type (name,value,intro) values(?,?,?)"
r, err := db.Exec(s, name, value, intro)
if err != nil {
fmt.Printf("err: %v\n", err)
} else {
i, _ := r.LastInsertId()
fmt.Printf("i: %v\n", i)
}
}
func main() {
...
insert("测试", "测试", "测试")
}
查询操作
...
type DictType struct {
id int
name string
value string
intro string
}
func queryOneRow(id int) {
s := "select * from dict_type where id = ?"
var dict_type DictType
err := db.QueryRow(s, id).Scan(&dict_type.id, &dict_type.name, &dict_type.value, &dict_type.intro)
if err != nil {
fmt.Printf("err: %v\n", err)
} else {
fmt.Printf("dict_type: %v\n", dict_type)
}
}
func qeuryManyRow() {
s := "select * from dict_type"
var dict_type DictType
r, err := db.Query(s)
defer r.Close()
if err != nil {
fmt.Printf("err: %v\n", err)
} else {
for r.Next() {
r.Scan(&dict_type.id, &dict_type.name, &dict_type.value, &dict_type.intro)
fmt.Printf("dict_type: %v\n", dict_type)
}
}
}
func main() {
...
qeuryManyRow()
}
更新操作
...
func update(name string, value string, intro string, id int) {
s := "update dict_type set name=?,value=?,intro=? where id=?"
r, err := db.Exec(s, name, value, intro, id)
if err != nil {
fmt.Printf("err: %v\n", err)
} else {
i, _ := r.LastInsertId()
fmt.Printf("i: %v\n", i)
}
}
func main() {
...
update("update", "update", "update", 51)
}
删除操作
...
func delete(id int) {
s := "delete from dict_type where id=?"
r, err := db.Exec(s, id)
if err != nil {
fmt.Printf("err: %v\n", err)
} else {
i, _ := r.RowsAffected()
fmt.Printf("i: %v\n", i)
}
}
func main() {
...
delete(51)
}