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
相关推荐
码界筑梦坊21 小时前
240-基于Python的医疗疾病数据可视化分析系统
开发语言·python·信息可视化·数据分析·毕业设计·echarts
2301_8035545221 小时前
C++ 锁类型大全详解
开发语言·c++
一只小bit1 天前
MySQL事务:如何保证ACID?MVCC到底如何工作?
数据库·mysql·oracle
wuwu_q1 天前
用通俗易懂方式,详细讲讲 Kotlin Flow 中的 map 操作符
android·开发语言·kotlin
曼巴UE51 天前
UE5 C++ Slate 画曲线
开发语言·c++·ue5
向葭奔赴♡1 天前
Spring IOC/DI 与 MVC 从入门到实战
java·开发语言
minji...1 天前
C++ 面向对象三大特性之一---多态
开发语言·c++
·云扬·1 天前
使用pt-archiver实现MySQL数据归档与清理的完整实践
数据库·mysql
散峰而望1 天前
基本魔法语言函数(一)(C语言)
c语言·开发语言·编辑器·github
weixin_46681 天前
安装Zabbix7
数据库·mysql·zabbix