从MySQL结果生成.CSV文件[重复]

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 {
        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)
        }
    }
}

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

</div>

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.

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

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)
}