wangjun
wangjun

Reputation: 709

Must I call *sql.Rows.Close() before *sql.Tx.Rollback() calling?

When I using sql package of golang, if I make a query within transaction, and encounter an error while calling rows.Scan(), which method should I call first after this point? *sql.Tx.Rollback() or *sql.Rows.Close()? Currently I call *sql.Rows.Close() before *sql.Tx.Rollback(), but I want to know, what will happen if I reverse this order?

tx, err := db.Begin()
if err != nil {
    ... // handle error
}


rows, err := tx.Query("sqlstmt")
if err != nil {
    ... // handle error
}


defer rows.Close() // can I use defer at this place, though it will be called after tx.Rollback()?


if err := rows.Scan(vars...); err != nil {
    if e := tx.Rollback(); e != nil {
        log(e)
        return e
    }
    return err
}

Upvotes: 1

Views: 1025

Answers (1)

beiping96
beiping96

Reputation: 644

https://go-review.googlesource.com/c/go/+/44812/

The code is here

It doesn't matter even if skip the rows.Close() within transaction

When the transaction has commit or rollback, the rows will be closed by transaction context.

Upvotes: 1

Related Questions