为了账号安全,请及时绑定邮箱和手机立即绑定

从 MySQL 结果生成 .CSV 文件

从 MySQL 结果生成 .CSV 文件

Go
RISEBY 2023-07-26 15:44:46
我正在尝试使用 Go 生成一个 CSV 文件,该文件将存储 MySQL 查询的转储。我目前可以将结果导出到预先存在的 CSV 文件,但我尝试在 main.go 运行后自动生成 CSV 文件。我尝试使用WriteFile,我知道它会将 CSV 文件写入指定的文件名。我知道这是设计使然,但我希望生成该文件。
查看完整描述

2 回答

?
交互式爱情

TA贡献1712条经验 获得超3个赞

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 时自动创建


查看完整回答
反对 回复 2023-07-26
?
小怪兽爱吃肉

TA贡献1852条经验 获得超1个赞

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)

}


查看完整回答
反对 回复 2023-07-26
  • 2 回答
  • 0 关注
  • 77 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信