Golang - 连接MySQL执行查询脚本

脚本如下,简单易用:

Go 复制代码
package main

import (
	"fmt"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

type BaseID struct {
	ID int64 `gorm:"primaryKey" json:"id"`
}

type Tasks struct {
	BaseID
	UUID        string  `gorm:"column:uuid;not null;unique;index" json:"uuid"`
	Name          string  `gorm:"column:name;type:varchar(128)" json:"name"`
	CreateTime    float64 `gorm:"column:create_time"  json:"create_time"`
}

func main() {
	// 连接 MySQL 数据库
	dsn := "root:**********@tcp(192.68.1.1:3306)/skyeye?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err.Error())
	}

	// 查询数据行数
	var count int64
	result := db.Model(&Tasks{}).Count(&count)
	//db.DBO.Model(&oldModels.Tasks{}).Where("is_delete = 0").Count(&totalCount)
	if result.Error != nil {
		panic(result.Error.Error())
	}

	fmt.Printf("表中共有 %d 行数据\n", count)
}

将Golang脚本编译成可执行二进制文件的命令:

windows:

bash 复制代码
# 要求在cmd命令行下执行 - 否则会报错
SET CGO_ENABLED=0&&SET GOOS=linux&&SET GOARCH=amd64&& go build -o query_count ./main.go
SET CGO_ENABLED=0&&SET GOOS=windows&&SET GOARCH=amd64&& go build -o query_count.exe ./main.go

linux:

bash 复制代码
env GOOS=linux  GOARCH=amd64 GO111MODULE=on GOPROXY=https://goproxy.cn,direct go build  -ldflags "-s -w" -o query_count  main.go
相关推荐
张张努力变强2 分钟前
C++ STL string 类:常用接口 + auto + 范围 for全攻略,字符串操作效率拉满
开发语言·数据结构·c++·算法·stl
xyq20244 分钟前
Matplotlib 绘图线
开发语言
m0_694845578 分钟前
tinylisp 是什么?超轻量 Lisp 解释器编译与运行教程
服务器·开发语言·云计算·github·lisp
春日见13 分钟前
如何创建一个PR
运维·开发语言·windows·git·docker·容器
C++ 老炮儿的技术栈16 分钟前
VS2015 + Qt 实现图形化Hello World(详细步骤)
c语言·开发语言·c++·windows·qt
派葛穆23 分钟前
Python-批量安装依赖
开发语言·python
斯普信专业组29 分钟前
构建基于MCP的MySQL智能运维平台:从开源服务端到交互式AI助手
运维·mysql·开源·mcp
MSTcheng.35 分钟前
【C++】C++11新特性(二)
java·开发语言·c++·c++11
晓131338 分钟前
第七章 【C语言篇:文件】 文件全面解析
linux·c语言·开发语言
愚者游世38 分钟前
Delegating Constructor(委托构造函数)各版本异同
开发语言·c++·程序人生·面试·改行学it