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.

1
  • Why are you doing this with Go at all, when you can do it directly with MySQL? Commented Sep 18, 2019 at 16:44

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.