簡體   English   中英

將數據保存到文件 golang sql 查詢

[英]Saving data to a file golang sql query

請幫幫我。 如何將收到的數據寫入文件? 我需要從 section_id,modified_by 寫入所有數據。

rows, err := db.Query("select section_id, modified_by from enrollment where rownum < 5")
    if err != nil {
        fmt.Println("Error running query")
        fmt.Println(err)
        return
    }
    defer rows.Close()

    var section_id string
    var modified_by string
    for cont := true; cont; cont = rows.NextResultSet() {
        for rows.Next() {
            err := rows.Scan(&section_id, &modified_by)
            if err != nil {
                fmt.Println(err)
            }
            fmt.Println(section_id, modified_by)
        }
    }

}

感謝您的任何幫助!

將循環替換為

f, err := os.Create("data.txt")
if err != nil {
    log.Fatalf("could not open file: %v", err)
}
defer f.Close()

for cont := true; cont; cont = rows.NextResultSet() {
    for rows.Next() {
        err := rows.Scan(&section_id, &modified_by)
        if err != nil {
            fmt.Println(err)
        }
        fmt.Println(section_id, modified_by)
        n, err := f.WriteString(fmt.Sprintf("%s modified %d", modified_by, section_id))
        if err != nil {
            log.Fatalf("could not write to file: %v", err)
        }
        log.Printf("Wrote %d bytes\n", n)
    }
}

您首先打開一個文件,檢查錯誤,然后在循環中再次將每一行寫入文件,並在兩者之間進行錯誤檢查。 有關更多示例,請參見此處

您可以使用json.MarshalIndent將數據保存為美化的json文件。

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
)

func ToJsonFile(path string, v interface{}) {
    bytes, _ := json.MarshalIndent(v, "", " ")

    if err := ioutil.WriteFile(path, bytes, 0644); err != nil {
        fmt.Println(err)
        panic(err)
    }
    fmt.Println("Saved the data as json file at " + path)
}

type Enrollment struct {
    SectionId  string `json:"section_id"`
    ModifiedBy string `json:"modified_by"`
}

func PersistData() error {
    // implement db here ...
    
    // array to put data together
    var data []*Enrollment

    rows, err := db.Query("select section_id, modified_by from enrollment where rownum < 5")
    if err != nil {
        fmt.Println("Error running query")
        fmt.Println(err)
        return err
    }
    defer rows.Close()

    for cont := true; cont; cont = rows.NextResultSet() {
        for rows.Next() {
            document := &Enrollment{}

            err := rows.Scan(&document.SectionId, &document.ModifiedBy)
            if err != nil {
                fmt.Println(err)
                return err
            }
            data = append(data, document)
            fmt.Println(document.SectionId, document.ModifiedBy)
        }
    }

    // persist data to a json file
    ToJsonFile("DATA.json", data)
    
    return nil
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM