0
1

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 のデータを読む (Read)

Last updated at Posted at 2021-01-31

プログラム

フォルダー構造

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

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

type City struct {
	Id           string
	Name         string
	Population   int
	Date_mod     string
}

// ----------------------------------------------------------------
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)
		}
	cities := []City{}

	db.Find(&cities)

	llx := len(cities)
	fmt.Println(llx)

	for it := 0; it < llx; it++{
		unit_aa := cities[it]
		fmt.Printf("%s\t",unit_aa.Id)
		fmt.Printf("%s\t",unit_aa.Name)
		fmt.Printf("%d\t",unit_aa.Population)
		fmt.Printf("%s\n",unit_aa.Date_mod)
	}

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

// ----------------------------------------------------------------

.env
config_mariadb.go
はこちら
Go: gorm で MariaDB のバージョンを表示

実行の準備

go mod init read
go mod tidy

実行

go run gorm_read.go config_mariadb.go

MariaDB

テーブル定義は次のようになっています。

mysql> show columns from city.cities;
+------------+-------------+------+-----+---------+-------+
| Field      | Type        | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| id         | varchar(10) | YES  |     | NULL    |       |
| name       | varchar(20) | YES  |     | NULL    |       |
| population | int         | YES  |     | NULL    |       |
| date_mod   | date        | YES  |     | NULL    |       |
+------------+-------------+------+-----+---------+-------+

確認したバージョン

$ go version
go version go1.20.1 linux/amd64
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?