英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论