2019-09-23 20:50



I'm attempting to generate a CSV file which would store a dump of a MySQL query, using Go.

I am currently able to export my results to a pre-existing CSV file, but I am trying to auto generate the CSV file once main.go is run. I've tried to use WriteFile, which I know will write a CSV file to the file name specified. I know this is by design, but I'd like the file to generate.

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

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

    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]


        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)

My goal is to have the OrdeTest.csv file to auto create itself when I run main.go

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • dongza1708 dongza1708 2年前

    sqltocsv.WriteFile(...) should create the file for you if it doesn't exist.

    Under the hood, it just uses os.Create(...) from the standard library.


    // 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()

    The documentation for 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)
    点赞 评论 复制链接分享