将数据保存到文件中的Golang SQL查询。

huangapple go评论88阅读模式
英文:

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)
        // 在这里将数据写入文件
    }
}

谢谢您的帮助!

英文:

Help me, pls. How can I write the received data on file? I need write all-data from section_id, modified_by.

rows, err := db.Query(&quot;select section_id, modified_by from enrollment where rownum &lt; 5&quot;)
	if err != nil {
		fmt.Println(&quot;Error running query&quot;)
		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(&amp;section_id, &amp;modified_by)
			if err != nil {
				fmt.Println(err)
			}
			fmt.Println(section_id, modified_by)
		}
	}

}

Thank you for any help!

答案1

得分: 0

用以下代码替换循环部分:

f, err := os.Create("data.txt")
if err != nil {
    log.Fatalf("无法打开文件:%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 修改了 %d", modified_by, section_id))
        if err != nil {
            log.Fatalf("无法写入文件:%v", err)
        }
        log.Printf("写入了 %d 字节\n", n)
    }
}

首先打开一个文件,并检查是否有错误,然后在循环中再次将每一行写入文件,并在其中进行错误检查。更多示例请参见这里

英文:

Replace the loop with

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

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

You first open a file, check for errors and then in the loop write every row to the file again with error checks in between. See here for more examples.

答案2

得分: 0

你可以使用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("已将数据保存为json文件,路径为:" + path)
}

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

func PersistData() error {
	// 在这里实现数据库操作...

	// 用于存放数据的数组
	var data []*Enrollment

	rows, err := db.Query("select section_id, modified_by from enrollment where rownum < 5")
	if err != nil {
		fmt.Println("运行查询时出错")
		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)
		}
	}

	// 将数据持久化为json文件
	ToJsonFile("DATA.json", data)

	return nil
}

以上是要翻译的内容。

英文:

You can save your data as a beautified json file using json.MarshalIndent.

package main
import (
&quot;encoding/json&quot;
&quot;fmt&quot;
&quot;io/ioutil&quot;
)
func ToJsonFile(path string, v interface{}) {
bytes, _ := json.MarshalIndent(v, &quot;&quot;, &quot; &quot;)
if err := ioutil.WriteFile(path, bytes, 0644); err != nil {
fmt.Println(err)
panic(err)
}
fmt.Println(&quot;Saved the data as json file at &quot; + path)
}
type Enrollment struct {
SectionId  string `json:&quot;section_id&quot;`
ModifiedBy string `json:&quot;modified_by&quot;`
}
func PersistData() error {
// implement db here ...
// array to put data together
var data []*Enrollment
rows, err := db.Query(&quot;select section_id, modified_by from enrollment where rownum &lt; 5&quot;)
if err != nil {
fmt.Println(&quot;Error running query&quot;)
fmt.Println(err)
return err
}
defer rows.Close()
for cont := true; cont; cont = rows.NextResultSet() {
for rows.Next() {
document := &amp;Enrollment{}
err := rows.Scan(&amp;document.SectionId, &amp;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(&quot;DATA.json&quot;, data)
return nil
}

huangapple
  • 本文由 发表于 2022年8月26日 21:45:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/73502000.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定