Golang において GORM を使って show tables (テーブル一覧を取得) したい。

環境

  • Go 1.x
  • MySQL 8.x

How To get database Tables list in go language (SHOW TABLES)

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

func main() {
	// Connect DB
	// https://github.com/go-sql-driver/mysql#examples
	db, err := gorm.Open("mysql", "username:password@tcp(localhost)/dbname?charset=utf8&parseTime=True&loc=Local")
	if err != nil {
		panic(err.Error())
	}
	
	// Raw use raw sql as conditions, won't run it unless invoked by other methods
	rows, err := db.Raw("show tables").Rows()
	if err != nil {
		panic(err.Error())
	}
	defer rows.Close()
	
	// Rows return `*sql.Rows` with given conditions
	// https://godoc.org/database/sql#Rows
	for rows.Next() {
		var table string
		if err := rows.Scan(&table); err != nil {
			panic(err.Error())
		}
		fmt.Printf(table)
	}
}

関連投稿