0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Go: gorm で MariaDB のバージョンを表示

Last updated at Posted at 2023-02-26

プログラム

フォルダー構造

$ tree -a
.
├── .env
├── config_mariadb.go
├── go.mod
├── go.sum
└── gorm_version.go
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
// ----------------------------------------------------------------
//
//	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
}

// ----------------------------------------------------------------
.env
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
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?