gorm的使用以及错误记录

package main
import (
       "fmt"
        "github.com/jinzhu/gorm"
        "github.com/sirupsen/logrus"
        _ "github.com/jinzhu/gorm/dialects/sqlite"
        "encoding/json"
        _ "reflect"

)

type Product struct {
    gorm.Model
    Code string
    Price uint
}

func main() {
    fmt.Println("in main")
    db,err :=gorm.Open("sqlite3","test.db")
    if err!=nil{
        panic("数据库连接失败")
    }
    defer db.Close()
    //创建
    db.AutoMigrate(&Product{})
    product:=&Product{Code: "L123",Price:1000}

    json_p,err:= json.Marshal(product)
        if err != nil {
    }
    logrus.Infof("json_p %v",string(json_p))
   //使用where的时候,后面需要使用Find指定当前表的model,也就是结构体。
    result:=db.Where("code=?","L123").Find(product)
   //go  type interface {} is interface with no method问题解决
    logrus.Infof("result %v",result.Value.(*Product).Price)
    db.First(product,1)
    db.First(product,"code = ?","L123")
    db.Model(product).Update("Price",3000)
    db.Delete(product)
}

go type interface {} is interface with no methods
因为返回的是interface类型,需要做转换才能使用
result.Value.(Product) 就是将interface{}专为Product之后再获取其Price字段的值。

猜你喜欢

转载自www.cnblogs.com/c-x-a/p/12275087.html