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
相关推荐
码少女7 小时前
MySQL--库与表的增删改查基础
java·数据库·mysql
打工的小王8 小时前
postgresql和mysql对比
数据库·mysql·postgresql
布莱克6058 小时前
Swift 循环与控制转移详解:从 for-in 到标签跳转
开发语言·ssh·swift·循环
敲上瘾9 小时前
Qt核心机制:信号与槽详解
开发语言·c++·qt·ui·qt6.3
联犀9 小时前
ai时代复杂项目的golang项目如何更好的与ai共舞:monorepo+gozero
开发语言·人工智能·golang
codeejun11 小时前
每日一Go·MySQL-15、慢查询日志实战分析(从 0 到 1 实战排查慢 SQL)
sql·mysql·golang
lcj251111 小时前
[C++] C++11
开发语言·c++·笔记
Decay__12 小时前
SQLServer 监控体系构建 —— sql_exporter + Prometheus + Grafana 全栈实战
运维·数据库·sql·mysql·架构
Evand J13 小时前
【MATLAB例程】基于IMM-CKF的AOA+测距融合的二维移动目标跟踪定位
开发语言·matlab·目标跟踪
飞奔的瓜牛13 小时前
Nacos 三节点集群部署手册:MySQL 持久化 + Nginx 负载均衡
mysql·nginx·负载均衡