duanqinjiao5244 2019-09-23 20:50
浏览 175
已采纳

从MySQL结果生成.CSV文件[重复]

I'm attempting to generate a CSV file which would store a dump of a MySQL query, using Go.

I am currently able to export my results to a pre-existing CSV file, but I am trying to auto generate the CSV file once main.go is run. I've tried to use WriteFile, which I know will write a CSV file to the file name specified. I know this is by design, but I'd like the file to generate.

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

My goal is to have the OrdeTest.csv file to auto create itself when I run main.go

</div>
  • 写回答

1条回答 默认 最新

  • dongza1708 2019-09-23 23:31
    关注

    sqltocsv.WriteFile(...) should create the file for you if it doesn't exist.

    Under the hood, it just uses os.Create(...) from the standard library.

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

    The documentation for 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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏