donglvmang8638 2018-10-26 05:17
浏览 43
已采纳

如何使用GO-MSSQLDB驱动程序获取最后插入的ID?

I gathered that SQL Server does not return last inserted id automatically and I need to do it manually with: OUTPUT INSERTED.ID within SQL insert statement.

How do I pick it up later in Go code?

The function in question is:

    func (sta *state) mkLogEntry(from time.Time, to time.Time, man bool) (id int64) {
    qry := "INSERT INTO ROMEExportLog(FromDate,ToDate,ExecutedAt,ExecutedManually,ExportWasSuccessful,UpdatedDaysIrregular) OUTPUT INSERTED.ID " +
        "VALUES(@FromDate,@ToDate,@ExecutedAt,@ExecutedManually,@ExportWasSuccessful,@UpdatedDaysIrregular)"
    res, err := sta.db.Exec(qry,
        sql.Named("FromDate", from),
        sql.Named("ToDate", to),
        sql.Named("ExecutedAt", time.Now()),
        sql.Named("ExecutedManually", man),
        sql.Named("ExportWasSuccessful", false),
        sql.Named("UpdatedDaysIrregular", false),
    )
    if err != nil {
        log.Fatal(err)
    }
    id, err = res.LastInsertId()

    if err != nil {
        log.Fatal(err)
    }
    return
}

The res.LastInsertId() returns There is no generated identity value.

  • 写回答

2条回答 默认 最新

  • dongshuiga2826 2018-10-26 06:00
    关注

    The reason for this is because PostgreSQL does not return you the last inserted id. This is because last inserted id is available only if you create a new row in a table that uses a sequence.

    If you actually insert a row in the table where a sequence is assigned, you have to use RETURNING clause. Something like this: INSERT INTO table (name) VALUES("val") RETURNING id.

    I am not sure about your driver, but in pq you will do this in the following way:

    lastInsertId := 0
    err = db.QueryRow("INSERT INTO brands (name) VALUES($1) RETURNING id", name).Scan(&lastInsertId)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持