golang learning go connect mysql

1. Mysql table creation

Create user table

CREATE TABLE `user` (
  `user_id` int NOT NULL AUTO_INCREMENT,
  `user_name` varchar(100) DEFAULT NULL,
  `user_code` varchar(100) NOT NULL,
  `password` varchar(100) NOT NULL,
  PRIMARY KEY (`user_id`),
  UNIQUE KEY `user_user_code_IDX` (`user_code`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

Two, mysql driver download

1. Create a new project directory wms

2. Open the cmd command window and enter the wms directory
insert image description here
3. Initialize the project

go mod init fa.com/wms

go mod init initialization command, fa.com/wms is the module path insert image description here
4. Download the go driver

go get github.com/go-sql-driver/mysql@latest

Execute the go get command to download the latest version of the go mysql driver
insert image description here

Three, mysql connection parameter configuration

Create a new mysqlutil.go to establish a mysql connection

package db

import (
	"database/sql"
	"fmt"
	"time"

	//注册驱动器 _下划线表示执行驱动中的init函数,不使用其他函数
	_ "github.com/go-sql-driver/mysql"
)
// 创建数据库连接
func ConnMySQL() *sql.DB {
    
    
	// 数据源名
	driverName := "mysql"
	// 用户名root
	// 密码1234
	// tcp协议连接
	// 数据库地址
	// 数据库 wms
	dataSourceName := "root" + ":" + "1234" + "@" + "tcp" + "(" + "127.0.0.1:3306" + ")" + "/" + "wms"
	db, err := sql.Open(driverName, dataSourceName)
	if err != nil {
    
    
		panic(err)
	}

	// 数据库设置
	db.SetConnMaxLifetime(time.Minute * 10)
	db.SetConnMaxIdleTime(time.Minute * 10)
	db.SetMaxOpenConns(10)
	db.SetMaxIdleConns(10)

	// 连接测试
	err = db.Ping()
	if err != nil {
    
    
		fmt.Println("数据库连接失败")
		panic(err)
	}
	return db
}

Four, mysql new data

Create a new user.go

// 包名
package user

import (
	"log"
	// 引入mysql数据库连接包
	"fa.com/wms/db"
)
// 定义user类型结构体
type User struct {
    
    
	UserId   int
	UserName string
	UserCode string
	Password string
}

// 向数据库新增一个User数据
func AddUser(u *User) {
    
    
	// 调用db包ConnMySQL()
	db := db.ConnMySQL()
	// 预编译保存sql创建 statement
	stmt, err := db.Prepare("INSERT INTO `user`	(user_name, user_code, password) VALUES (?, ?, ?)")
	// err 不等空则statement创建失败
	if err != nil {
    
    
		// 打印错误信息
		log.Fatal(err)
		// 抛出错误信息,阻止程序继续运行
		panic(err)
	}
	// 在函数运行结束时关闭statement
	defer stmt.Close()
	// 执行保存sql
	// _下划线 表示忽略函数返回的sql.Result值
	_, err = stmt.Exec(u.UserName, u.UserCode, u.Password)
	if err != nil {
    
    
		// 打印错误信息
		log.Fatal(err)
		// 抛出错误信息,阻止程序继续运行
		panic(err)
	}
}

Five, mysql delete data

func DeleteById(userId int) {
    
    
	db := db.ConnMySQL()
	// 预编译删除sql创建 statement
	stmt, err := db.Prepare("delete from `user`  where user_id = ?")
	// err 不等空则statement创建失败
	if err != nil {
    
    
		// 打印错误信息
		log.Fatal(err)
		// 抛出错误信息,阻止程序继续运行
		panic(err)
	}
	// 在函数运行结束时关闭statement
	defer stmt.Close()
	// 执行删除sql
	// _下划线 表示忽略函数返回的sql.Result值
	_, err = stmt.Exec(userId)
	if err != nil {
    
    
		// 打印错误信息
		log.Fatal(err)
		// 抛出错误信息,阻止程序继续运行
		panic(err)
	}
}

Six, mysql modify data

func UpdateUser(u *User) {
    
    
	db := db.ConnMySQL()
	// 预编译更新sql创建 statement
	stmt, err := db.Prepare("UPDATE `user` SET user_name=?, user_code=?, password=? WHERE user_id=?")
	// err 不等空则statement创建失败
	if err != nil {
    
    
		// 打印错误信息
		log.Fatal(err)
		// 抛出错误信息,阻止程序继续运行
		panic(err)
	}
	// 在函数运行结束时关闭statement
	defer stmt.Close()
	// 执行更新sql
	// _下划线 表示忽略函数返回的sql.Result值
	_, err = stmt.Exec(u.UserName, u.UserCode, u.Password, u.UserId)
	if err != nil {
    
    
		// 打印错误信息
		log.Fatal(err)
		// 抛出错误信息,阻止程序继续运行
		panic(err)
	}
}

Seven, mysql query data

func QueryUserByCode(code string) []User {
    
    
	// 调用db包ConnMySQL()
	db := db.ConnMySQL()
	// 预编译查询sql创建 statement
	stmt, err := db.Prepare("SELECT user_id, user_name, user_code, password FROM `user` WHERE user_code= ?")
	if err != nil {
    
    
		log.Fatal(err)
		panic(err)
	}
	defer stmt.Close()
	// 执行查询sql,返回查询结果rows
	rows, err := stmt.Query(code)
	if err != nil {
    
    
		// 打印错误信息
		log.Fatal(err)
		// 抛出错误信息,阻止程序继续运行
		panic(err)
	}
	// 定义User切片
	s := make([]User, 0)
	// 遍历rows
	for rows.Next() {
    
    
		u := User{
    
    }
		// 扫描rows的每一列并保存数据到User对应字段
		err := rows.Scan(&u.UserId, &u.UserName, &u.UserCode, &u.Password)
		if err != nil {
    
    
			// 打印错误信息
			log.Fatal(err)
			// 抛出错误信息,阻止程序继续运行
			panic(err)
		}// 扫描后的user加入到切片
		s = append(s, u)
	}
	return s
}

The above code is written using vscode, and the directory structure is shown in the figure below:
insert image description here

Guess you like

Origin blog.csdn.net/weixin_56349119/article/details/125732259