登录
首页 >  Golang >  Go问答

从 MySQL 结果生成 .CSV 文件

来源:stackoverflow

时间:2024-04-25 21:36:36 102浏览 收藏

目前golang学习网上已经有很多关于Golang的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《从 MySQL 结果生成 .CSV 文件》,也希望能帮助到大家,如果阅读完后真的对你学习Golang有帮助,欢迎动动手指,评论留言并分享~

问题内容

我正在尝试使用 go 生成一个 csv 文件,该文件将存储 mysql 查询的转储。

我目前可以将结果导出到预先存在的 csv 文件,但我尝试在 main.go 运行后自动生成 csv 文件。我尝试使用 writefile,我知道它会将 csv 文件写入指定的文件名。我知道这是设计使然,但我希望生成该文件。

rows, _ := db.Query("SELECT * FROM orderTest limit 100;")

    err := sqltocsv.WriteFile("orderTest.csv", rows)
    if err != nil {
        panic(err)
    }

    columns, _ := rows.Columns()
    count := len(columns)
    values := make([]interface{}, count)
    valuePtrs := make([]interface{}, count)

    for rows.Next() {
        for i := range columns {
            valuePtrs[i] = &values[i]
        }

        rows.Scan(valuePtrs...)

        for i, col := range columns {
            val := values[i]

            b, ok := val.([]byte)
            var v interface{}
            if ok {
                v = string(b)
            } else {
                v = val
            }

            fmt.Println(col, v)
        }
    }
}

我的目标是让 ordetest.csv 文件在运行 main.go 时自动创建


解决方案


sqltocsv.writefile(...) 应该为您创建该文件(如果该文件不存在)。

在底层,它只使用标准库中的 os.create(...)

github.com/joho/sqltocsv/sqltocsv.go:

// writefile writes the csv to the filename specified, return an error if problem
func (c converter) writefile(csvfilename string) error {
    f, err := os.create(csvfilename)
    if err != nil {
        return err
    }

    err = c.write(f)
    if err != nil {
        f.close() // close, but only return/handle the write error
        return err
    }

    return f.close()
}

os.create(...) 的文档:

// Create creates the named file with mode 0666 (before umask), truncating
// it if it already exists. If successful, methods on the returned
// File can be used for I/O; the associated file descriptor has mode
// O_RDWR.
// If there is an error, it will be of type *PathError.
func Create(name string) (*File, error) {
    return OpenFile(name, O_RDWR|O_CREATE|O_TRUNC, 0666)
}

本篇关于《从 MySQL 结果生成 .CSV 文件》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>