登录
首页 >  Golang >  Go问答

在Golang中,如何将查询结果切片传递给Struct字段?

来源:stackoverflow

时间:2024-02-07 19:18:23 372浏览 收藏

从现在开始,努力学习吧!本文《在Golang中,如何将查询结果切片传递给Struct字段?》主要讲解了等等相关知识点,我会在golang学习网中持续更新相关的系列文章,欢迎大家关注并积极留言建议。下面就先一起来看一下本篇正文内容吧,希望能帮到你!

问题内容

我一直在尝试将我的 sql 查询结果输入到我的 react 前端中显示的结构中,但是我的 db.select() 只输出到切片中,我不确定如何将结果放入 sum 字段中在我的结构中。

结果在我的 vscode 控制台中显示良好,如下所示。

[{1382 } {1367 } {1342 } {662 } {1863 } {1977 } {2269 }]

但是我找不到任何方法将我的 result 变量输入到我的 structs sum 字段中。

我的代码在下面,任何帮助都会很棒!

type Tag struct { Sum string json:"sum" Query_desc string json:"Query_Desc" Query_start_date string json:"Query_start_date" Query_end_date string json:"Query_end_date" Current_date string json:"Current_date" Error_info string json:"Error_Info" }

func handler(w http.ResponseWriter, r http.Request) { w.Header().Set("Access-Control-Allow-Origin", "") w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")

db, err := sqlx.Connect("mysql", "****")

date_1 := r.FormValue("date_1") 
date_2 := r.FormValue("date_2")

var tag Tag

result := []Tag{}

Query := ("SELECT ROUND(SUM(duration)/3600,0) sum FROM sessions WHERE (app_id = 'idrice' OR app_id ='idrios' OR app_id ='' OR **** =''OR app_id ='') AND date(created ) between ? and ? and time(created ) between '16:00:00' and '18:00:00' AND (media_src='' OR media_src='' OR media_src='' OR media_src='' OR ****='' OR ****='****') GROUP BY date(created)")

err = db.Select(&result, Query, date_1, date_2)

tag.Query_desc = "Listener Hours" 
tag.Query_start_date = date_1 
tag.Query_end_date = date_2 dt := time.Now() 
tag.Current_date = dt.Format("01-02-2006 15:04:05") 

if err != nil { tag.Error_info = err.Error() }

j, err := json.Marshal(tag) if err != nil { w.WriteHeader(http.StatusBadRequest) w.Write([]byte((err.Error()))) return } w.Write(j)

}

func main() { http.HandleFunc("/", handler) log.Fatal(http.ListenAndServe(":8081", nil)) }

正确答案


package main

import (
    "encoding/json"
    "log"
    "net/http"
    "strconv"
    "time"

    "github.com/jmoiron/sqlx"
)

type Tag struct {
    Sum              string `json:"sum"`
    Query_desc       string `json:"query_desc"`
    Query_start_date string `json:"query_start_date"`
    Query_end_date   string `json:"query_end_date"`
    Current_date     string `json:"current_date"`
    Error_info       string `json:"error_info"`
}

func handler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Access-Control-Allow-Origin", "")
    w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")

    db, err := sqlx.Connect("mysql", "****")

    if err != nil {
        log.Fatal(err)
    }

    date_1 := r.FormValue("date_1")
    date_2 := r.FormValue("date_2")

    var tag Tag

    result := []Tag{}

    Query := ("SELECT ROUND(SUM(duration)/3600,0) sum FROM sessions WHERE (app_id = 'idrice' OR app_id ='idrios' OR app_id ='' OR **** =''OR app_id ='') AND date(created ) between ? and ? and time(created ) between '16:00:00' and '18:00:00' AND (media_src='' OR media_src='' OR media_src='' OR media_src='' OR ****='' OR ****='****') GROUP BY date(created)")

    err = db.Select(&result, Query, date_1, date_2)

    tag.Query_desc = "Listener Hours"
    tag.Query_start_date = date_1
    tag.Query_end_date = date_2
    dt := time.Now()
    tag.Current_date = dt.Format("01-02-2006 15:04:05")

    // define a aggregateSum variable to hold the sum of all the values in the result set

    var aggregateSum int
    // loop through the result set and add the values to the aggregateSum variable
    for _, v := range result {
        d, err := strconv.Atoi(v.Sum) // convert the string value to an integer
        if err != nil {
            log.Fatal(err)
        }
        aggregateSum += d
    }

    tag.Sum = strconv.Itoa(aggregateSum) // convert the integer to a string and assign it to the Sum field of the tag struct


    if err != nil {
        tag.Error_info = err.Error()
    }

    j, err := json.Marshal(tag)
    if err != nil {
        w.WriteHeader(http.StatusBadRequest)
        w.Write([]byte((err.Error())))
        return
    }
    w.Write(j)

}

func main() {
    http.HandleFunc("/", handler)
    log.Fatal(http.ListenAndServe(":8081", nil))
}

以上就是《在Golang中,如何将查询结果切片传递给Struct字段?》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>