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 想用adb命令做一个通话软件,播放录音
  • ¥30 Pytorch深度学习服务器跑不通问题解决?
  • ¥15 部分客户订单定位有误的问题
  • ¥15 如何在maya程序中利用python编写领子和褶裥的模型的方法
  • ¥15 Bug traq 数据包 大概什么价
  • ¥15 在anaconda上pytorch和paddle paddle下载报错
  • ¥25 自动填写QQ腾讯文档收集表
  • ¥15 DbVisualizer Pro 12.0.7 sql commander光标错位 显示位置与实际不符
  • ¥15 android 打包报错
  • ¥15 关于stm32的问题