go操作mysql数据库

104 阅读1分钟

安装驱动

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
	}
	// 尝试与数据库连接 校验dsn是否正确
	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) // 输出插入数据的id
	}
}

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
        // 使用QueryRow后调用Scan方法 否则持有的数据库连接不会被释放
	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() {
	...
	// queryOneRow(51)
	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) // 输出插入数据的id
	}
}

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)
}