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
相关推荐
月光水岸New32 分钟前
Ubuntu 中建的mysql数据库使用Navicat for MySQL连接不上
数据库·mysql·ubuntu
软件黑马王子35 分钟前
C#初级教程(4)——流程控制:从基础到实践
开发语言·c#
我爱松子鱼36 分钟前
mysql之规则优化器RBO
数据库·mysql
闲猫38 分钟前
go orm GORM
开发语言·后端·golang
丁卯4041 小时前
Go语言中使用viper绑定结构体和yaml文件信息时,标签的使用
服务器·后端·golang
李白同学2 小时前
【C语言】结构体内存对齐问题
c语言·开发语言
人间打气筒(Ada)3 小时前
MySQL主从架构
服务器·数据库·mysql
和道一文字yyds3 小时前
MySQL 中的索引数量是否越多越好?为什么?如何使用 MySQL 的 EXPLAIN 语句进行查询分析?MySQL 中如何进行 SQL 调优?
数据库·sql·mysql
黑子哥呢?3 小时前
安装Bash completion解决tab不能补全问题
开发语言·bash
青龙小码农3 小时前
yum报错:bash: /usr/bin/yum: /usr/bin/python: 坏的解释器:没有那个文件或目录
开发语言·python·bash·liunx