"go
package main
import (
"fmt"
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql"
"time"
)
type Userinfo struct {
Uid int `orm:"pk"`
Username string
Departname string
Created time.Time
}
func init() {
orm.RegisterModel(new(Userinfo))
orm.RegisterDataBase("default", "mysql", "momaek:123456@/test?charset=utf8")
}
func main() {
o := orm.NewOrm()
user := Userinfo{Username: "hello", Departname: "wd"}
id, err := o.Insert(&user)
fmt.Printf("ID:%d, Err: %v\n ", id, err)
user.Uid = 3
user.Created = time.Now()
user.Departname = "wakkkk"
num, err := o.Update(&user)
fmt.Printf("Num:%d ,ERR: %v\n", num, err)
u := Userinfo{Username: "hello"}
err = o.Read(&u)
fmt.Println(u)
fmt.Printf("ERR: %v\n", err)
num, err = o.Delete(&u)
fmt.Printf("NUM: %d, Err: %v\n", num, err)
}
"
代码是这样的。然后运行报错:
ID:47, Err: <nil>
Num:0 ,ERR: <nil>
{0 hello 0001-01-01 00:00:00 +0000 UTC}
ERR: missed pk value
NUM: 0, Err: missed pk value
beego's ORM should use
id int
as the primary key by defaultThere must be a primary key when reading, updating, and deleting. It should only be required when creating, because the primary key is auto. Your primary key setting is correct
In fact, it is recommended that the primary key is like this
Then when this code, such as read, beego orm is executed, it will find the primary key, get the value of the primary key, and then execute
select fields from user where uid = value
, your If the value of the primary key does not exist (0), the ORM cannot execute the select, and of course an error will be reportedhttp://jinzhu.me/gorm/curd.ht...
I feel this ORM is more useful.
By first querying, find out whether the changed primary key has a value Read()
Insert Update Delete