gorm 如何读取数据呢?

package dryad

import (
    "time"
    "fmt"
    "log"
    // "gnome/init"
    "net/http"
    "github.com/gin-gonic/gin"
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/postgres"
)


func Hlogin(c *gin.Context) {
    var phone string = c.Param("phone")
    var pwd string = c.Param("pwd")
    if (phone==""||pwd==""){
        c.Data(http.StatusOK, "text/json", []byte(`{"status":"false","info":""}`))
    }
    // gnome.Db.Close()
    Db,errs:=gorm.Open("postgres","user=postgres dbname=july password=123456789 host=192.168.1.113 port=5432 sslmode=disable")
    if errs!=nil{
        log.Fatal( fmt.Sprint("数据库连接%s",errs.Error() ))
    }
    defer Db.Close()
    var huser = Human{}
    qhuser:=Db.Where("phone = ?" ,phone).First(&huser)
    if err:=qhuser.Error; err!=nil{
        c.Data(http.StatusOK, "text/json", []byte(`{"status":"false","info":"用户名不存在"}`))
    }
    fmt.Println(huser)
    fmt.Println(huser.name)
    // fmt.Println(    qhuser )
    c.Data(http.StatusOK, "text/json",[]byte(fmt.Sprintf(`{"status":"true","info":"成功","name":"%s"}`,huser.name)))
    
    // c.Data(http.StatusOK, "text/json", []byte(`{"status":"true","bo":}`))
    return
}

type Human struct{
    sex int `gorm:"SMALLINT"`
    id int `gorm:"primary_key"`
    cookieid string  `gorm:"size:80"`
    phone string  `gorm:"size:18;not null;unique"`
    name string  `gorm:"size:25;not null"`
    password string  `gorm:"size:25;not null"`
    onLining bool
    onBlacklist bool
    onBlacklistCreatTime time.Time
    speechless bool
    speechlessCreatTime time.Time
    headImg string `gorm:"size:255"`
    typeStyle int
    email string `gorm:"type:varchar(255);unique_index"`
    born_y int
    born_m int
    born_d int
    grade int
    declaration string `gorm:"size:255"`
    createTime  time.Time
    updateTime  time.Time
}
func (Human) TableName() string {
    return "human"
}

postgresql 没有sql 查询的日子的记录,代码里面 huser 也获取不到数据。 帮我看看代码有问题没!

阅读 10.1k
2 个回答

问题在于,你的model中字段的定义,要以大写开头,按照规范来做, 你自己试试

这样

Sex int `gorm:"SMALLINT"`
ID int `gorm:"primary_key"`
Cookieid string  `gorm:"size:80"`
Phone string  `gorm:"size:18;not null;unique"`
Name string  `gorm:"size:25;not null"`

而且这里你error处理的有问题的

 qhuser:=Db.Where("phone = ?" ,phone).First(&huser)
    if err:=qhuser.Error; err!=nil{
        c.Data(http.StatusOK, "text/json", []byte(`{"status":"false","info":"用户名不存在"}`))
    }

这边error不是只有ErrRecordNotFound,还有数据库执行查询失败的错误

mode 写在一个文件里面 应该首字母大写的,之前表示python 生产。 命名规则和gorm命名规则不一样。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题