三十六、Gin注册功能-检查账号是否存在

一、初始化

1、在cms.go中添加数据库连接方法

func connDB(app *CmsApp) {
	mysqlDB, err := gorm.Open(mysql.Open("root:rootroot@tcp(localhost:3306)/?charset=utf8mb4&parseTime=True&loc=Local"))
	if err != nil {
		panic(err)
	}
	db, err := mysqlDB.DB()
	if err != nil {
		panic(err)
	}
	//最大连接数
	db.SetMaxOpenConns(4)
	//最大空闲连接,一般为最大连接数/2
	db.SetMaxIdleConns(2)
	mysqlDB = mysqlDB.Debug()
	app.db = mysqlDB
}

2、在cms.go中进行初始化数据库连接方法

type CmsApp struct {
	db *gorm.DB
}
func NewCmsApp() *CmsApp {
	app := &CmsApp{}
	connDB(app)
	return app
}

二、完成account表的字段映射model

type Account struct {
	ID        int64     `gorm:"column:id;primaryKey;autoIncrement:true"`
	UserId    string    `gorm:"column:user_id"`
	Password  string    `gorm:"column:password"`
	Nickname  string    `gorm:"column:nickname"`
	CreatedAt time.Time `gorm:"column:created_at"`
	UpdatedAt time.Time `gorm:"column:updated_at"`
}

func (a Account) TableName() string {
    //在数据表中省略了库名,写在了这里因为这样更灵活,方便做分库分表
	table := "cms_account.account"
	return table
}

三、完成account的dao方法

package dao

import (
	"ConnetMain/internal/model"
	"gorm.io/gorm"
)
//声明为gorm的db
type AccountDao struct {
	db *gorm.DB
}
//调用时引入初始化CmsApp.db
func NewAccountDao(db *gorm.DB) *AccountDao {
	return &AccountDao{db: db}
}
//具体实现方法,查询是否存在这个user_id
func (a *AccountDao) IsExist(userID string) (bool, error) {
	var account model.Account
	err := a.db.Where("user_id=?", userID).First(&account).Error
    //返回查询不到错误返回false
	if err == gorm.ErrRecordNotFound {
		return false, err
	}
    //返回错误不为空
	if err != nil {
		return false, err
	}
	return true, nil
}

四、具体调用

在register.go中进行调用IsExist方法

//声明dao包下NewAccountDao
accountDao := dao.NewAccountDao(c.db)
//调用IsExist方法
	isExist, err := accountDao.IsExist(req.UserID)
//发送错误则终止程序
	if err != nil {
		ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
//返回true则代表能吃查询到相关数据则表示账号已经存在
	if isExist {
		ctx.JSON(http.StatusBadRequest, gin.H{"err": "账号已存在"})
	}

五、实验

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值