Golang从数据库获取信息时遇到问题如何解决
Golang从数据库获取信息时遇到问题如何解决 你好! 希望你能帮助我
第一个文件
func (b *Auth) GetInfo(login string) {
var auth models.Auth
if strings.Contains(login, "@") {
auth = db.GetDb().
Table("profile").
Select("id, cell_phone, email").
Where("email = ?", login).
First(&b)
return auth
} else {
auth = db.GetDb().
Table("profile").
Select("id, cell_phone, email").
Where("phone = ?", login).
First(&b)
return auth
}
}
第二个文件
type Auth struct {
ID int `json:"id"`
ExtID string `json:"ext_id"`
CellPhone string `json:"cell_phone"`
Email string `json:"email"`
}
func Authentication(ctx *gin.Context) {
login := ctx.Query("login")
authentication := models.Auth{}
authentication.GetDriverInfo(login)
ctx.JSON(http.StatusOK, authentication)
}
第三个文件
func main() {
db.Initialize()
router := gin.Default()
core := router.Group("/api/private")
{
core.GET("/profile", info.Authentication)
}
}
我收到的响应体字段为空 建表语句和插入语句我就不展示了 我需要修改什么?
更多关于Golang从数据库获取信息时遇到问题如何解决的实战教程也可以访问 https://www.itying.com/category-94-b0.html
2 回复
getdriverinfo 是什么?如果这只是拼写错误,你实际想说的是获取信息,那么你应该使用它的返回值而不是忽略它。或者修改方法中的 b 而不是创建一个新的 Auth 结构体。
更多关于Golang从数据库获取信息时遇到问题如何解决的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
你的代码有几个问题导致返回空字段。主要问题在于数据库查询方法的错误使用和返回值处理不当。
问题分析:
First(&b)应该查询到auth变量,而不是直接修改b- 方法没有正确处理返回值
- 查询条件字段名不匹配
修改后的代码:
第一个文件修改:
func (b *Auth) GetInfo(login string) error {
var auth Auth
query := db.GetDb().
Table("profile").
Select("id, cell_phone, email")
if strings.Contains(login, "@") {
query = query.Where("email = ?", login)
} else {
query = query.Where("cell_phone = ?", login)
}
result := query.First(&auth)
if result.Error != nil {
return result.Error
}
// 将查询结果赋值给接收器
b.ID = auth.ID
b.CellPhone = auth.CellPhone
b.Email = auth.Email
return nil
}
第二个文件修改:
type Auth struct {
ID int `json:"id"`
ExtID string `json:"ext_id"`
CellPhone string `json:"cell_phone"`
Email string `json:"email"`
}
func Authentication(ctx *gin.Context) {
login := ctx.Query("login")
authentication := models.Auth{}
err := authentication.GetInfo(login)
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{
"error": "获取用户信息失败",
})
return
}
ctx.JSON(http.StatusOK, authentication)
}
关键修改点:
- 查询方法修正:使用
First(&auth)将结果存储到局部变量,然后赋值给接收器 - 字段名统一:将
phone改为cell_phone与结构体字段和数据库字段保持一致 - 错误处理:添加适当的错误处理机制
- 返回值修正:方法现在返回
error而不是models.Auth
调试建议:
检查数据库连接和表结构,确保 profile 表包含 id, cell_phone, email 字段,并且数据存在。可以通过在查询前后添加日志来确认查询条件和结果。

