Having trouble getting a string out of my pgx query using row_to_json in sql in golang

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

Having trouble getting a string out of my pgx query using row_to_json in sql in golang

问题

如果你使用row_to_json等方法将返回的行格式化为JSON文本,有没有办法从pgx查询中获取一个字符串?

func handler(w http.ResponseWriter, r *http.Request) {
    rows, err := DB.Query("select row_to_json(rows) as data from (select * from userinfo) rows;")

    w.Header().Set("Content-Type", "application/json")
    w.Write(rows)
}

如果你想要从pgx查询中获取一个字符串,你可以使用row_to_json函数将返回的行格式化为JSON文本,然后将其转换为字符串。在上面的代码中,rows变量应该是一个JSON文本字符串,你可以直接将其写入HTTP响应中。

英文:

Is there a way to get back a string from a pgx query if you use row_to_json etc. to format the returned rows as json text?

func handler(w http.ResponseWriter, r *http.Request) {
    rows, err := DB.Query("select row_to_json(rows) as data from (select * from userinfo) rows;")

	w.Header().Set("Content-Type", "application/json")
    w.Write(rows)
}

答案1

得分: 1

好的,下面是翻译好的内容:

好的,这是我所做的。我最终使用了QueryRow而不是Query,因为我只期望得到一个JSON结果。然后我使用row.Scan()将结果获取为一个字符串,然后使用w.Write([]byte(result))将得到的字符串写入响应。

如果你的结果中有多行数据,你可能需要以不同的方式处理结果。可能这个链接可以帮到你

func handler(w http.ResponseWriter, r *http.Request) {
    var result string
    err := postgresConn.QueryRow(`我的SQL查询`).Scan(&result)
    switch {
    case err == sql.ErrNoRows:
        log.Printf("没有该ID的用户。")
        w.Header().Set("Content-Type", "application/json")
        w.Write([]byte("{}"))
    case err != nil:
        log.Println(err)
        w.WriteHeader(http.StatusInternalServerError)
    default:
        w.Header().Set("Content-Type", "application/json")
        w.Write([]byte(result))
    }
}
英文:

Ok, here's what I did. I ended up using QueryRow instead of Query because I'm only expecting one json result. I then use row.Scan() to get the result into a string and then w.Write([]byte(result)) to write the resulting string to the response.

If you have multiple rows in your result, you might need to handle the result differently. Possibly this might help?

func handler(w http.ResponseWriter, r *http.Request) {
    var result string
    err := postgresConn.QueryRow(`My SQL Query`).Scan(&result)
    switch {
    case err == sql.ErrNoRows:
	    log.Printf("No user with that ID.")
	    w.Header().Set("Content-Type", "application/json")
	    w.Write([]byte("{}"))
    case err != nil:
	    log.Println(err)
        w.WriteHeader(http.StatusInternalServerError)
    default:
	    w.Header().Set("Content-Type", "application/json")
	    w.Write([]byte(result))
    }
}

huangapple
  • 本文由 发表于 2015年11月25日 14:40:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/33909997.html
匿名

发表评论

匿名网友

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

确定