0

I'm trying to export the results of a MySQL query to a .csv file via Go.

In my current code, I am able to print out the results of my query in a command window, but I'd like to export those results via .csv file.

My current code looks like this:

results, err := db.Query("SELECT id, testId, testtwoId, testthreeId, testfourId  FROM TestTable LIMIT 100")
    if err != nil {
        panic(err.Error())
    }

    for results.Next() {
        var estTable TestTable

        err = results.Scan(&orderEvent.id, &orderEvent.testId, &orderEvent.eventId, &orderEvent.createTime, &orderEvent.updateTime)
        if err != nil {
            panic(err.Error())
        }
        log.Println(TestTable.id, TestTable.testId, TestTable.testtwoId, TestTable.testthreeId, TestTable.testfourId)
    }

When running my file, I am able to view my tables data without issue, but I'd still like to export this data via .csv.

I was looking around and found some code for .csv functionality, however I'm uncertain how to apply this to my current code.

I thought about applying something like this:


    file, err := os.Create("result.csv")
    checkError("Cannot create file", err)
    defer file.Close()

    writer := csv.NewWriter(file)
    defer writer.Flush()

    for _, value := range data {
        err := writer.Write(value)
        checkError("Cannot write to file", err)
    }
}

func checkError(message string, err error) {
    if err != nil {
        log.Fatal(message, err)
    }
}

However, I am currently not sure how to apply this in my code.

Flimzy
  • 60,850
  • 13
  • 104
  • 147
Zl1987
  • 45
  • 6
  • Why are you doing this with Go at all, when you can do it [directly with MySQL](https://stackoverflow.com/questions/356578/how-to-output-mysql-query-results-in-csv-format)? – Flimzy Sep 18 '19 at 16:44

1 Answers1

1

csv.Write in stdlib gets an array of strings, so you should do something like this in your for-loop:

writer.Write([]string{TestTable.id, TestTable.testId, TestTable.testtwoId, TestTable.testthreeId, TestTable.testfourId})

If some of those fields of TestTable are not strings, you have to convert them to strings as necessary.

Flimzy
  • 60,850
  • 13
  • 104
  • 147
Burak Serdar
  • 27,223
  • 3
  • 14
  • 34