如何使用csv.Writer输出MySQL数据 [英] How to use csv.Writer to output MySQL data

查看:55
本文介绍了如何使用csv.Writer输出MySQL数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过Go将MySQL查询的结果导出到.csv文件.

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

在当前代码中,我可以在命令窗口中打印出查询结果,但是我想通过.csv文件导出这些结果.

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.

我当前的代码如下:

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

运行文件时,我可以无问题地查看表数据,但我仍想通过.csv导出此数据.

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.

我环顾四周,发现了一些.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.

推荐答案

csv.stdlib中的write获取字符串数组,因此您应该在for循环中执行以下操作:

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

如果TestTable的某些字段不是字符串,则必须根据需要将它们转换为字符串.

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

这篇关于如何使用csv.Writer输出MySQL数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆