简体   繁体   English

如何在 golang 应用程序中使用 gorm 进行数据库/表转储(.sql 文件)?

[英]How to take a DB/Table dump (.sql file) using gorm in a golang application?

I am using a Golang Application and the Gorm ORM to connect to a Database.我正在使用 Golang 应用程序和 Gorm ORM 连接到数据库。 How can I take a table dump (.sql file) through the ORM?如何通过 ORM 进行表转储(.sql 文件)? Is it even possible?甚至可能吗?

If it is possible, is it possible to use a where clause (like in mysqldump --where="..." ).如果可能,是否可以使用where子句(如mysqldump --where="..." )。

It's not possible, mysqldump is a separate utility command-line tool like mysqlimport, mysqladmin etc. It's not a MySQL query.这是不可能的,mysqldump 是一个单独的实用命令行工具,如 mysqlimport、mysqladmin 等。它不是 MySQL 查询。

But You should be able to run this raw query using gorm to store query results to file https://dev.mysql.com/doc/refman/8.0/en/select-into.html但是您应该能够使用 gorm 运行此原始查询以将查询结果存储到文件https://dev.mysql.com/doc/refman/8.0/en/select-into.ZFC35FDC70D5FC69D2698EZ83A83

There is no Function for dump in GORM. GORM 中没有用于转储的 Function。

But you can get table data into struct object.但是您可以将表数据放入结构 object 中。 And you can save it as json or in any format for your backup reference.您可以将其保存为 json 或任何格式以供备份参考。

Since, GORM internally uses sql.因为,GORM 内部使用 sql。 You can try with this logic.你可以试试这个逻辑。

Refer this link: https://gist.github.com/xigh/58e138f856bd0946dc748b0f0dc44b02参考这个链接: https://gist.github.com/xigh/58e138f856bd0946dc748b0f0dc44b02

func main() {

    dbSrc := fmt.Sprintf("%s:%s@%s/%s?parseTime=true", *dbUser, *dbPass, *dbHost, *dbName)

    db, err := sql.Open("mysql", dbSrc)
    if err != nil {
        log.Fatalf("sql.Open failed: %v", err)
    }
    defer db.Close()

    // sql.Open() does not establish any connections to the database ...

    err = db.Ping()
    if err != nil {
        log.Fatalf("db.Ping failed: %v", err)
    }

    tables, err := showTables(db)
    if err != nil {
        log.Fatalf("showTables failed: %v\n", err)
    }

    for _, table := range tables {
        ds, err := describe(db, table)
        if err != nil {
            log.Fatalf("describe failed: %v\n", err)
        }

        fmt.Printf("%s:\n", table)
        for _, d := range ds {
            fmt.Printf("\t%-20s %s\n", d.Name, d.Type)
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM