GET blob from sql database Golang

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

GET blob from sql database Golang

问题

以下是翻译好的内容:

import (
    "database/sql"
    "encoding/json"
    "fmt"

    _ "github.com/go-sql-driver/mysql"
)

type User struct {
    Name    string  `json:"name"`
    Picture []uint8 `json:"picture"`
}

func main() {
    // 直接查询
    rows, err := db.Query("SELECT name, picture FROM ms_users") // 数据库中的picture字段是longblob类型
    checkErr(err)

    var usr User
    for rows.Next() {
        err = rows.Scan(&usr.Name, &usr.Picture)
        checkErr(err)
    }

    jsn, err := json.Marshal(usr)
    fmt.Printf("%v", string(jsn))
}

使用上述代码,我只能获取到name的值,但是picture字段为空。我该如何将数据库中的blob值存储到结构体中?任何答案都将不胜感激!谢谢!

英文:
 import (
	   "database/sql"
	   "encoding/json"
	   "fmt"

	   _ "github.com/go-sql-driver/mysql"
   ) 
   type User struct {
       Name string  `json:name`
       Picture []uint8 `json:picture`
    }
    func main(){
       //straight to the query
       rows, err := 'SELECT name, picture FROM ms_users' // picture is longblob type in database
       checkErr(err)
      
       var usr User
       for rows.Next(){
          err = rows.Scan(&usr.Name, &usr.Picture)
          checkErr(err)
       }
       jsn, err := json.Marshal(usr)
       fmt.Printf("%v, "string(jsn))
    }

With above code, I only get name value but the picture is empty.
How do I store blob value from databse to struct ?
Any answer will be appreciated! thank you!

答案1

得分: 10

我对GO相对较新,在寻找类似问题的解决方案时遇到了这个问题,我能够找到一个解决方案。

当你从数据库获取BLOB数据时,它以[]byte类型返回,你的结构体可以像下面这样:

type User struct {
   Name string  `json:name`
   Picture []byte`json:picture`
}

我猜你可以根据需要处理字节数组。在我的情况下,我需要一个JSON对象,所以我将其解组为一个类型为interface{}的变量。

英文:

I'm relatively new to GO I encountered this question while searching a solution for a similar problem I was able to find a solution.

When you get BLOB data from the database you get it as type []byte your struct can look like this below

type User struct {
   Name string  `json:name`
   Picture []byte`json:picture`
}

I guess you can process the byte array according to you need later. In my case I needed a JSON object so I unmarshalled it to a type interface{} variable.

huangapple
  • 本文由 发表于 2017年5月12日 00:48:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/43921387.html
匿名

发表评论

匿名网友

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

确定