亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從 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 關注
  • 164 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號