csv - 从 MySQL 结果生成 .CSV 文件

标签 csv go

<分区>

我正在尝试使用 Go 生成一个 CSV 文件,该文件将存储 MySQL 查询的转储。

我目前能够将我的结果导出到预先存在的 CSV 文件中,但我试图在运行 main.go 后自动生成 CSV 文件。我试过使用 WriteFile,我知道它会将 CSV 文件写入指定的文件名。我知道这是设计使然,但我希望生成文件。

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

我的目标是让 OrdeTest.csv 文件在我运行 main.go 时自动创建自己

最佳答案

sqltocsv.WriteFile(...) 应该为您创建文件(如果它不存在)。

在底层,它只是使用标准库中的 os.Create(...)

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

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

关于csv - 从 MySQL 结果生成 .CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58070027/

相关文章:

json - 如何解析json post请求

go - $GOPATH 目录和磁盘空间

c# - Csv 文件到 Sql 数据库 C#

python - Pandas : Replace old column values and plot new column values with respect to equations

go - 如何上传 gzip 压缩文件而不将所有内容读入内存

go - 如何在for循环中使用两个initStmt?

assembly - 堆栈变量在去?

java - 根据字符串到长整型映射将定界字符串转换为定界长整型

java - 在用 Ant 编译的文件中找不到主类

python - 读取 CSV 并绘制彩色折线图