gorm: 安装使用

一,官方网站:

https://gorm.io/

如图:

 

二,安装:

从命令行安装gorm

$ go get -u gorm.io/gorm
go: downloading gorm.io/gorm v1.25.12
go: downloading github.com/jinzhu/now v1.1.5
go: downloading golang.org/x/text v0.19.0
go: downloading golang.org/x/text v0.20.0
go: added github.com/jinzhu/inflection v1.0.0
go: added github.com/jinzhu/now v1.1.5
go: upgraded golang.org/x/text v0.19.0 => v0.20.0
go: added gorm.io/gorm v1.25.12

 

安装相应的数据库驱动,我们这里选择mysql

$ go get -u gorm.io/driver/mysql
go: downloading gorm.io/driver/mysql v1.5.7
go: downloading github.com/go-sql-driver/mysql v1.7.0
go: downloading github.com/go-sql-driver/mysql v1.8.1
go: downloading filippo.io/edwards25519 v1.1.0
go: added filippo.io/edwards25519 v1.1.0
go: added github.com/go-sql-driver/mysql v1.8.1
go: added gorm.io/driver/mysql v1.5.7

三,测试编写代码

1,建立连接:

package config

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"time"
)

var (
	DBLink *gorm.DB
)

func SetupDBLink() (error) {
	var err error

	dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=%s&parseTime=%t&loc=Local",
		"username",
		"password",
		"127.0.0.1:3306",
		"databasename",
		"utf8",
		true, )

	//dsn:="username:password@tcp(127.0.0.1:3306)/basename?charset=utf8&parseTime=True&loc=Local";

	DBLink, err = gorm.Open(mysql.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Info),})
	//DBLink.Logger.LogMode(logger.Info)
	if err != nil {
		return err
	}

	sqlDB, _ := DBLink.DB()

	// SetMaxIdleConns 设置空闲连接池中连接的最大数量
	sqlDB.SetMaxIdleConns(10)
	// SetMaxOpenConns 设置打开数据库连接的最大数量
	sqlDB.SetMaxOpenConns(30)
	// SetConnMaxLifetime 设置了连接可复用的最大时间
	sqlDB.SetConnMaxLifetime(time.Hour)

	return nil
}

 

2,查询数据:

type Article struct {
	//定义文章的struct
	Id uint `gorm:"column:id;primaryKey"`
	Title string `gorm:"column:title;" json:"title"`
	Demo string  `gorm:"column:demo;" json:"demo"`
	Content string `gorm:"column:content;" json:"content"`
}

func (Article) TableName() string {
	return "article"
}

func (dc *ArticleController) GetArticle(c *fiber.Ctx) error {

	fields := []string{"id", "title","demo","content"}
	articleOne:=&Article{}
	articleId := 2424

	articleOutOne:=&ArticleOut{}

	err := config.DBLink.Select(fields).Where("id=?",articleId).First(&articleOne).Error
	if (err != nil) {
		fmt.Println(err)
	} else {
		fmt.Println(articleOne)
	}

	myMap:=fiber.Map{}

	myMap["Title"] = "书店新上图书列表"
	myMap["Article"] = articleOne
	fmt.Println(myMap)
    return c.Render("article/info", myMap)
}

 

posted @ 2024-11-23 09:18  刘宏缔的架构森林  阅读(36)  评论(0编辑  收藏  举报