自学内容网 自学内容网

使用Go语言的gorm框架查询数据库并分页导出到Excel实例(包含源代码,可以直接运行)

基本配置

配置文件管理

添加依赖 go get github.com/spf13/viper,支持 JSON, TOML, YAML, HCL 等格式的配置文件。

在项目根目录下面新建 conf 目录,然后新建 application.yml 文件,此文件需要忽略版本控制。每次修改后,记得同步修改 conf/application.yml.demo 文件,让别人也知道你添加或修改了哪些内容。

server:
  port: 8080
datasource:
  driverName: mysql
  host: "127.0.0.1"
  port: "3306"
  database: go-demo-2025
  username: root
  password: "123456"
  charset: utf8
  loc: Asia/Shanghai

配置初始化: common/initialization.go

// 配置初始化
func InitConfig() {
   
workDir, _ := os.Getwd()               //获取目录对应的路径
viper.SetConfigName("application")     //配置文件名
viper.SetConfigType("yml")             //配置文件类型(后缀名)
viper.AddConfigPath(workDir + "/conf") //执行go run对应的路径配置
fmt.Println(workDir)
err := viper.ReadInConfig()
if err != nil {
   
panic(err)
}
}

数据库配置: 使用 gorm 初始化数据库配置,参考 common/database.go 文件

var DB *gorm.DB

// https://gorm.io/zh_CN/docs/index.html
func InitDB() *gorm.DB {
   
//从配置文件中读取数据库配置信息
host := viper.GetString("datasource.host")
port := viper.Get("datasource.port")
database := viper.GetString("datasource.database")
username := viper.GetString("datasource.username")
password := viper.GetString("datasource.password")
charset := viper.GetString("datasource.charset")
loc := viper.GetString("datasource.loc")
args := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=true&loc=%s",
username,
password,
host,
port,
database,
charset,
url.QueryEscape(loc))
//fmt.Println(args)
db, err := gorm.Open(mysql.Open(args), &gorm.Config{
   
Logger: logger.Default.LogMode(logger.Info), //配置日志级别,打印出所有的sql
})
if err != nil {
   
fmt.Println(err)
panic("failed to connect database, err: " + err.Error())
}
DB = db
return db
}

命令行工具: Cobra

Cobra是Go的CLI框架。它包含一个用于创建强大的现代CLI应用程序的库和一个用于快速生成基于Cobra的应用程序和命令文件的工具。

简单理解, 类似于 thinkphp 封装的 php think xxx 的命令行工具.

Cobra 官网: https://cobra.dev

快速入门

  • 安装: go get github.com/spf13/cobra
  • 入口文件: command.go
  • 核心文件: cmd/cobra.go

基本用法

测试Demo: command/testCmd.go

执行: go run command.go testCmd --paramA 100 --paramB 200 hello your name

输出:

--- test 运行 ---
参数个数: 3
100
200
0=>hello
1=>your
2=>name

更多参考: https://www.cnblogs.com/niuben/p/13886555.html

生成mock数据

SQL准备

CREATE TABLE `user` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `user_id` bigint(20) unsigned NOT NULL COMMENT '用户编号',
  `name` varchar(255) NOT NULL DEFAULT '' COMMENT '用户姓名',
  `age` tinyint(4) unsigned NOT NULL DEFAULT '0' COMMENT '用户年龄',
  `address` varchar(255) NOT NULL DEFAULT '' COMMENT '地址',
  `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '添加时间',
  `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `key_user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

gorm自动生成结构体代码

需要引入gorm.io/gen扩展,参考代码:gorm_generate_db_struct.go

package main

import (
"gorm.io/driver/mysql"
"gorm.io/gen"
"gorm.io/gorm"
"strings"
)

func main() {
   
// 初始化配置
common.InitConfig()

// 连接数据库
db := common.InitDB()

// 生成实例
g := gen.NewGenerator(gen.Config{
   
// 相对执行`go run`时的路径, 会自动创建目录
OutPath: "old_crm_models/query",

// WithDefaultQuery 生成默认查询结构体(作为全局变量使用), 即`Q`结构体和其字段(各表模型)
// WithoutContext 生成没有context调用限制的代码供查询
// WithQueryInterface 生成interface形式的查询代码(可导出), 如`Where()`方法返回的就是一个可导出的接口类型
Mode: gen.WithDefaultQuery | gen.WithQueryInterface,

// 表字段可为 null 值时, 对应结体字段使用指针类型
//FieldNullable: true, // generate pointer when field is nullable

// 表字段默认值与模型结构体字段零值不一致的字段, 在插入数据时需要赋值该字段值为零值的, 结构体字段须是指针类型才能成功, 即`FieldCoverable:true`配置下生成的结构体字段.
// 因为在插入时遇到字段为零值的会被GORM赋予默认值. 如字段`age`表默认值为10, 即使你显式设置为0最后也会被GORM设为10提交.
// 如果该字段没有上面提到的插入时赋零值的特殊需要, 则字段为非指针类型使用起来会比较方便.
FieldCoverable: false, // generate pointer when field has default value, to fix problem zero value cannot be assign: https://gorm.io/docs/create.html#Default-Values

// 模型结构体字段的数字类型的符号表示是否与表字段的一致, `false`指示都用有符号类型
FieldSignable: false

原文地址:https://blog.csdn.net/rxbook/article/details/142600138

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!