gpt4 book ai didi

mysql - 如何从 MySQL 中选择数据然后将其附加到新结构并将其转换为字节

转载 作者:数据小太阳 更新时间:2023-10-29 03:25:34 24 4
gpt4 key购买 nike

我想使用 Go 语言从 MySQL 数据库中读取数据。脚本是这样的

func GetAllCountry() []*Country{

dbConnection := db.ConnectMySQL()

rows, err := dbConnection.Query("SELECT id, country_code, country_name, phone_code, icon FROM country;")
if err != nil {
log.Fatal(err)
}
defer rows.Close()

country := new(Country)
var countries []*Country
for rows.Next() {
err := rows.Scan(&country.id, &country.country_code, &country.country_name, &country.phone_code, &country.icon)
if err != nil {
log.Fatal(err)
}
countries = append(countries, country)
fmt.Println(country)
}
return countries
}

返回的数据将保存到对象结构中。结构是这样的

type Country struct {
id int `json:"Country.id"`
country_code string `json:"Country.country_code"`
country_name string `json:"Country.country_name"`
phone_code string `json:"Country.phone_code"`
icon string `json:"Country.icon"`
}

在其他文件中,我正在创建一个函数来获取所有数据。我调用该函数,然后将其转换为 []byte,因为它曾经将其发送到 MessageBroker。

这里是把它转换成[]byte的函数

func GetCountry(msg string) []byte {

// country := new(countryModel.Country)
var countries []*countryModel.Country

countries = countryModel.GetAllCountry()
log.Println("Show result: ", countries)

jsResult, err := json.Marshal(countries)

if err != nil {
logger.Error(err, "Failed on GetCountry")
}


log.Println("Show result JSON: ", jsResult)

return jsResult
}

但是GetCountry函数返回的结果不是我想要的。在那个函数中,我得到了

[
{},
{}
]

我在我的控制台上显示数据。

&{1 ID Indonesia +62 no-data}
&{2 MY Malaysia +60 no-data}
2017/03/20 17:55:27 Show result: [0xc8200ba410 0xc8200ba410]
2017/03/20 17:55:27 Show result JSON: [91 123 125 44 123 125 93]

请帮忙。

最佳答案

正如@M-AbdelRahman 在评论中提到的,您的Country 结构字段需要导出(那些以大写字母开头的字段)因为json .Marshal 跳过未导出的字段(以小写字母开头的字段),这就是您要返回的原因 {}

type Country struct {
Id int `json:"Country.id"`
CountryCode string `json:"Country.country_code"`
CountryName string `json:"Country.country_name"`
PhoneCode string `json:"Country.phone_code"`
Icon string `json:"Country.icon"`
}

您的扫描必须相应地更改。

err := rows.Scan(&country.Id, &country.CountryCode, &country.CountryName, &country.PhoneCode, &country.Icon)

关于mysql - 如何从 MySQL 中选择数据然后将其附加到新结构并将其转换为字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42901974/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com