dqd78456 2018-08-10 04:33
浏览 100
已采纳

如何创建要插入但随后返回插入数据的事务

I am working on a REST API so I am trying to implement a way for users to create a new service ticket.

Everything is working fine except for when it comes to storing things in the db (postgres).

Here's a snippet of the transaction once it is generated:

BEGIN;

INSERT INTO service_request (id, ...)
VALUES (...);

INSERT INTO media (id, filename, ...)
VALUES (...),
(...),
(...);

INSERT INTO servicerequest_media(service_request_id, media_id)
values (..., ...),
(..., ...),
(...,...);

COMMIT;

Using sqlx prepared statements, I know that the result contains some metadata such as the last inserted id. However, how can I add a select query to my transaction and get the results of that query?

stmt, err := s.db.Prepare(CREATE_SERVICE_REQUEST)
if err != nil {
    //// 
}
res, err := stmt.Exec()
if err != nil {
    ////
}

Or, do I need to do a 2nd query to get the result?

I am pretty new to this, so please let me know if I need to give more context.

  • 写回答

1条回答 默认 最新

  • dse55384 2018-08-10 05:04
    关注

    Exec does not return the rows created or inserted. It only returns the last inserted element id.

    If you would like to get the rows, you can consider using Query or QueryRow.

    rows, err := stmt.Query()
    if rows.Next {
        // declare variable of any type string, int or struct
        rows.Scan(&variable) // string, int
        // or
        rows.Scan(&variable.field1, &variable.field2) // where field1, field2 are the properties of your struct
        // do whatever you want with the variable
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题