去gorm中显示MariaDB的版本

程序

文件夹结构

$ tree -a
.
├── .env
├── config_mariadb.go
├── go.mod
├── go.sum
└── gorm_version.go
// ----------------------------------------------------------------
//
//	gorm_version.go
//
//					Feb/26/2023
//
// ----------------------------------------------------------------
package main

import (
	"fmt"
	"os"
	"gorm.io/gorm"
	"gorm.io/driver/mysql"
)

// ----------------------------------------------------------------
func main() {
	fmt.Fprintln(os.Stderr,"*** 開始 ***")

	host,user,password,data_base := config_mariadb_proc()

	dsn := user + ":" + password + "@tcp(" + host + ":3306)/" + data_base + "?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}

	result := map[string]interface{}{}

	db.Raw("SELECT VERSION ()").Scan(&result)

	fmt.Println(result)

	fmt.Fprintln(os.Stderr,"*** 終了 ***")
}

// ----------------------------------------------------------------
// ----------------------------------------------------------------
//
//	config_mariadb.go
//
//					Feb/23/2023
//
// ----------------------------------------------------------------
package main

import (
	"os"
	"github.com/joho/godotenv"
)

// ----------------------------------------------------------------
func config_mariadb_proc()(string, string, string, string) {
	err := godotenv.Load(".env")
	if err != nil {
		panic(err)
	}

	host := os.Getenv("host")
	user := os.Getenv("user")
	password := os.Getenv("password")
	data_base := os.Getenv("data_base")

	return host,user,password,data_base
}

// ----------------------------------------------------------------
host = 'localhost'
user = 'scott'
password = 'tiger123'
data_base = 'city'

准备执行

go mod init version
go mod tidy

执行结果

$ go run gorm_version.go config_mariadb.go
*** 開始 ***
map[VERSION ():10.11.2-MariaDB]
*** 終了 ***

确认版本

$ go version
go version go1.20.1 linux/amd64