Home > Net >  Saving data to a file golang sql query
Saving data to a file golang sql query

Time:08-27

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

}

Thank you for any help!

CodePudding user response:

Replace the loop with

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

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.

CodePudding user response:

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

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
}
  • Related