读MySQL数据库所有表并输出见表语句
package main
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type ShowTablesRes struct {
// 注意这里也要改数据库名
TableName string `gorm:"column:Tables_in_${database}"`
}
type CreateRes struct {
Table string
CreateTable string `gorm:"column:Create Table"`
}
func main() {
dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", "${username}", "${password}", "${ip}:${port}", "${database}")
// useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=true&serverTimezone=GMT%2B8"
fmt.Println(dsn)
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
var showTablesRes []ShowTablesRes
db.Raw("show tables").Scan(&showTablesRes)
// fmt.Println(&showTablesRes)
for _, v := range showTablesRes {
// fmt.Printf("%s\n", v.TableName)
var createRes []CreateRes
showTableStruct := "show create table " + v.TableName
db.Raw(showTableStruct).Scan(&createRes)
fmt.Printf("%s;\n", createRes[0].CreateTable)
}
}