Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GET blob from sql database Golang

Tags:

go

 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!

like image 522
Angger Avatar asked Mar 10 '23 02:03

Angger


1 Answers

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.

like image 175
Manesh Avatar answered Mar 14 '23 21:03

Manesh