Heim > Fragen und Antworten > Hauptteil
"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
阿神2017-04-17 11:17:39
beego的orm默认应该把id int
作为主键
read, update, delete的时候必须有主键,应该只有create的时候不需要,因为主键是auto的。你主键设置是正确的
Uid int `orm:"pk"`
其实建议主键是这样的
Id int
然后这段代码,比如read,beego orm 执行的时候,会找到主键,获取主键的值value,然后执行select fields from user where uid = value
,你的主键的值不存在(0),orm就没法执行select, 当然会报错
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)