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
相关推荐
自由与自然3 分钟前
栅格布局常用用法
开发语言·前端·javascript
_codemonster7 分钟前
python易混淆知识点(十六)lambda表达式
开发语言·python
小梁努力敲代码7 分钟前
Java多线程--单例模式
java·开发语言
Percep_gan8 分钟前
解决-bash: /usr/bin/yum: No such file or directory
开发语言·bash
缺点内向17 分钟前
如何在 C# 中将 Word 文档转换为 EMF(增强型图元文件)
开发语言·c#·word·.net
老华带你飞19 分钟前
学生宿舍管理|基于java + vue学生宿舍管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
Filotimo_27 分钟前
在java后端开发中,redis的用处
java·开发语言·redis
superman超哥43 分钟前
仓颉Option类型的空安全处理深度解析
c语言·开发语言·c++·python·仓颉
MyBFuture1 小时前
C# 哈希表与堆栈队列实战指南
开发语言·windows·c#·visual studio
网安_秋刀鱼1 小时前
【java安全】java安全基础
java·开发语言·安全·web安全