duanlun2827 2017-05-11 16:48
浏览 822

从SQL数据库Golang获取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条回答 默认 最新

  • douxian0279 2019-02-15 09:21
    关注

    I 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.

    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!