xorm插入数据库后返回主键自增id

golang使用xorm连接数据库后,插入结构体,无法返回自增主键id,饭后的主键id都是0。经过研究发现,如果给结构体id设置xorm tag,则会默认id为0,不会返回插入成功后的主键id。

xorm文档中如下描述

 1 package main
 2 
 3 import (
 4     "fmt"
 5     "time"
 6 
 7     _ "github.com/go-sql-driver/mysql"
 8     "github.com/go-xorm/xorm"
 9 )
10 
11 type User struct {
12     // 如果此处 `xorm:"id"`,则插入数据的时候,会默认为0,插入成功后不会把新插入的id返回,如果想得到插入后的主键id,则id不需要写`xorm:"id"`
13     Id      int64     //`xorm:"id"`
14     Name    string    `xorm:"name"`
15     Created time.Time `xorm:"created"`
16     Updated time.Time `xorm:"updated"`
17     Deleted time.Time `xorm:"deleted"`
18 }
19 
20 // 设置user结构体对应的表名
21 func (User) TableName() string {
22     return "test_user_2"
23 }
24 
25 func main() {
26     engine, err := xorm.NewEngine("mysql", "root:123456@tcp(10.10.30.99:3306)/test?charset=utf8")
27     if err != nil {
28         fmt.Println("connect mysql is failed, err:", err)
29     }
30 
31     u := &User{
32         Name: "aaa",
33     }
34     // 可插入多条engine.Insert(u1,u2)
35     affecte, err := engine.Insert(u)
36     if err != nil {
37         fmt.Println("insert is failed,err:", err)
38     }
39     fmt.Println("affect=", affecte, u.Id)
40 }

猜你喜欢

转载自www.cnblogs.com/chaselogs/p/10088326.html