将数据保存到文件golang-sql查询



请帮帮我。如何将收到的数据写入文件?我需要从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 bytesn", 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
}

最新更新