-3

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

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Zl1987
  • 53
  • 8
  • 1
    What problem are you having? – Adrian Sep 23 '19 at 21:02
  • I don't know how to auto generate a csv file, right now the csv file has to already be created in order for my results to be written to it. – Zl1987 Sep 23 '19 at 21:35
  • 1
    [The code](https://github.com/joho/sqltocsv/blob/ddc1b19/sqltocsv.go#L79) clearly shows that the file will be created if necessary. How do you come to the conclusion that it must already exist? – Peter Sep 23 '19 at 22:23
  • 2
    You already asked this exact question a few days ago. Don't post duplicate questions. – Jonathan Hall Sep 24 '19 at 06:00

1 Answers1

1

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)
}
pjmonk
  • 119
  • 5