MySQL表结构转Golang结构体工具

有没有好用的工具可以将MySQL表结构自动转换成Golang结构体?最近在写一个Go项目,需要频繁操作数据库,手动写struct太麻烦了。希望工具能支持字段类型映射、标签生成(如json和gorm)、注释转换等功能。最好能支持命令行或在线转换,求推荐!

2 回复

推荐工具:gormtsql2go。支持 MySQL 表自动生成 Golang 结构体,带 gorm 标签,简单高效。

更多关于MySQL表结构转Golang结构体工具的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


推荐使用以下工具将 MySQL 表结构自动转换为 Golang 结构体:

1. 在线工具

SQL-to-Go (https://sql-to-go.vercel.app/)

  • 直接粘贴 SQL 建表语句
  • 实时生成 Go 结构体
  • 支持字段标签(json、gorm)

2. 命令行工具

xo (https://github.com/xo/xo)

# 安装
go get github.com/xo/xo

# 使用示例
xo mysql://user:pass@localhost/dbname -o models

3. Go 代码实现示例

package main

import (
    "database/sql"
    "fmt"
    _ "github.com/go-sql-driver/mysql"
)

func generateStruct(db *sql.DB, tableName string) {
    rows, err := db.Query(`
        SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE 
        FROM INFORMATION_SCHEMA.COLUMNS 
        WHERE TABLE_NAME = ? AND TABLE_SCHEMA = DATABASE()`,
        tableName)
    if err != nil {
        panic(err)
    }
    defer rows.Close()
    
    fmt.Printf("type %s struct {\n", tableName)
    for rows.Next() {
        var columnName, dataType, nullable string
        rows.Scan(&columnName, &dataType, &nullable)
        
        goType := mysqlTypeToGoType(dataType, nullable)
        fmt.Printf("    %s %s `json:\"%s\"`\n", 
            toCamelCase(columnName), goType, columnName)
    }
    fmt.Println("}")
}

func mysqlTypeToGoType(mysqlType, nullable string) string {
    var goType string
    switch mysqlType {
    case "int", "tinyint", "smallint", "mediumint":
        goType = "int"
    case "bigint":
        goType = "int64"
    case "varchar", "text", "char":
        goType = "string"
    case "decimal", "float", "double":
        goType = "float64"
    case "datetime", "timestamp":
        goType = "time.Time"
    default:
        goType = "string"
    }
    
    if nullable == "YES" {
        return "*" + goType
    }
    return goType
}

推荐使用

  • 简单需求:使用在线工具 SQL-to-Go
  • 项目集成:使用 xo 命令行工具
  • 自定义需求:参考代码示例自行实现

这些工具能显著提高开发效率,自动处理字段类型映射和标签生成。

回到顶部