亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何從 golang 訪問 mysql db 中的 JSON 列

如何從 golang 訪問 mysql db 中的 JSON 列

Go
Cats萌萌 2023-01-03 10:01:31
我在 mysql 中有一個表,其中包含 3 列配置文件字符串、userInformation JSON、徽章字符串。輪廓  用戶信息    徽章https://ps.w.org/metronet-profile-picture/assets/icon-256x256.png?rev=2464419   {"name": "Suzan Collins", "points": 10000, "countryName": "波蘭"} 資產/batcherPage/gold.png這是我的結構:type BatchersData struct {    ProfileURL      string          `json:"profileUrl"`    UserInformation UserInformation `json:"userInformation"`    Badge           string          `json:"badge"`}type UserInformation struct {    Points      int64  `json:"points"`    Name        string `json:"name"`    CountryName string `json:"countryName"`}我想要做的是在此表上進行選擇查詢,即 GET 并檢索所有信息..使用此代碼,我訪問了 Profile 和 Badge :func getBatchers(c *gin.Context) {    var batchers []BatchersData    rows, err := db.Query("SELECT profileUrl, badge FROM Batchers_page_db")    if err != nil {        return    }    defer rows.Close()    for rows.Next() {        var batcher BatchersData        if err := rows.Scan(&batcher.ProfileURL, &batcher.Badge); err != nil {            return        }        batchers = append(batchers, batcher)    }    if err := rows.Err(); err != nil {        return    }    c.IndentedJSON(http.StatusOK, batchers)}但我也想訪問 JSON 列,即 UserInformation。我知道查詢將是rows, err := db.Query("SELECT * FROM Batchers_page_db")但我必須更改此聲明if err := rows.Scan(&batcher.ProfileURL, &batcher.Badge);我試過這樣做:但沒有任何效果rows.Scan(&batcher.ProfileURL,&batcher.UserInformation, &batcher.Badge);
查看完整描述

2 回答

?
一只萌萌小番薯

TA貢獻1795條經驗 獲得超7個贊

您需要實現Scan接口文檔以將數據映射到 JSON。在這里試試這個:

func (u * UserInformation) Scan(value interface{}) error {

  b, ok := value.([]byte)

  if !ok {

    return errors.New("type assertion to []byte failed")

  }

  return json.Unmarshal(b, &u)

}


查看完整回答
反對 回復 2023-01-03
?
千萬里不及你

TA貢獻1784條經驗 獲得超9個贊

從 Batchers_page_db 中選擇 JSON_EXTRACT(userInformation,'$.name') 作為 profileName, JSON_EXTRACT(userInformation,'$.points') 作為 userPoints

未經測試,但類似這樣的方法會起作用,但請確保您的數據庫字段必須是 JSON 類型。


查看完整回答
反對 回復 2023-01-03
  • 2 回答
  • 0 關注
  • 218 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號