【问题标题】:How to get id of last inserted row from sqlx?如何从 sqlx 获取最后插入的行的 id?
【发布时间】:2019-05-28 04:24:43
【问题描述】:

我想取回使用sqlx插入MySql数据库的最后一篇文章的ID:

resultPost, err := shared.Dbmap.Exec("INSERT INTO post (user_id, description, link) VALUES (?, ?, ?)", userID, title, destPath)
if err != nil {
    log.Println(err)
    c.JSON(
        http.StatusInternalServerError,
        gin.H{"error": "internal server error"})
}

fmt.Println("resultPost is:", resultPost)

问题是resultPost被打印为对象:

resultPost is: {0xc420242000 0xc4202403a0}

所以我想知道提取刚刚插入的行的 id 的正确方法是什么?

【问题讨论】:

    标签: mysql sql go sql-insert sqlx


    【解决方案1】:

    ExecResult 的返回值并不是直接访问的——它是一个对象,有两个方法可以调用,其中一个是LastInsertId()

    lastId, err := resultPost.LastInsertId()
    if err != nil {
        panic(err)
    }
    fmt.Println("LastInsertId: ", lastId)
    

    【讨论】:

    • 已修复。学习直接阅读文档对您大有帮助:)
    • @BravoDelta:最好只编辑带有更正的问题,而不是留下最终将被删除的评论。不过感谢指正。现在已经更新了。
    【解决方案2】:

    看起来你只需要:

    resultPost.LastInsertId()
    

    更多信息请在this documentation中搜索LastInsertId

    【讨论】:

    • LastInsertId is not supported by this driver 是我在使用 postgres 时得到的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-10
    • 2019-11-21
    • 1970-01-01
    • 1970-01-01
    • 2014-07-07
    • 1970-01-01
    相关资源
    最近更新 更多