go语言之操作数据库

1.操作mysql数据库

  • demo.go
package main

import (
	"database/sql"
	"fmt"

	_ "github.com/go-sql-driver/mysql"
)

var student struct {
	id         int
	name       string
	province   string
	city       string
	addr       string
	score      int
	enrollment string
}

func CheckError(err error) {
	if err != nil {
		fmt.Println(err)
		return
	}
}

func query(db *sql.DB) {
	rows, err := db.Query("select name,city,score,enrollment from student;")
	CheckError(err)
	for rows.Next() {
		err := rows.Scan(&student.name, &student.city, &student.score, &student.enrollment)
		CheckError(err)
		fmt.Println(student.name, student.city, student.score, student.enrollment)
	}
}

func insert(db *sql.DB) {
	sql := "insert into student(name,province,city,enrollment) values(?,?,?,?),(?,?,?,?)"
	res, err := db.Exec(sql, "宁静", "贵州", "贵阳", "2021-08-13", "黄晓明", "山东", "青岛", "2021-08-14")
	CheckError(err)
	lastid, err := res.LastInsertId()
	CheckError(err)
	fmt.Println(lastid)

	affect, err := res.RowsAffected()
	CheckError(err)
	fmt.Println(affect)
}

func update(db *sql.DB) {
	sql := "update student set name=? where id=?"
	res, err := db.Exec(sql, "杨戬", 4)
	CheckError(err)

	lastid, err := res.LastInsertId()
	CheckError(err)
	fmt.Println(lastid)

	affect, err := res.RowsAffected()
	CheckError(err)
	fmt.Println(affect)
}

func delete(db *sql.DB) {
	sql := "delete from student where city=?"
	res, err := db.Exec(sql, "成都")
	CheckError(err)

	lastid, err := res.LastInsertId()
	CheckError(err)
	fmt.Println(lastid)

	affect, err := res.RowsAffected()
	CheckError(err)
	fmt.Println(affect)
}

func replace(db *sql.DB) {
	// replace 跟 insert 类似, 有则修改,没有则创建记录
	sql := "replace into student(name,province,city,enrollment) values(‘红红‘, ‘山西‘, ‘太原‘, ‘2021-05-12‘)"
	res, err := db.Exec(sql)
	CheckError(err)

	lastid, err := res.LastInsertId()
	CheckError(err)
	fmt.Println(lastid)

	affect, err := res.RowsAffected()
	CheckError(err)
	fmt.Println(affect)
}

func write(db *sql.DB, sql string) {
	res, err := db.Exec(sql)
	CheckError(err)

	affect, err := res.RowsAffected()
	CheckError(err)
	fmt.Println(affect)
}

func main() {
	dns := "root:passwd@2021@tcp(172.30.1.128:3306)/day12?charset=utf8"
	db, err := sql.Open("mysql", dns)
	CheckError(err)

	// insert(db)
	// delete(db)
	// update(db)
	// query(db)
	// replace(db)
	sql := "insert into student(name,province,city,enrollment) values(‘李世民‘, ‘陕西‘, ‘西安‘, ‘2021-05-20‘)"
	write(db, sql)
}

go语言之操作数据库

上一篇:MySQL数据库使用utf8编码后中文仍显示??


下一篇:企业微信机器人-监控磁盘和应用可用率