Reputation: 1063
In Golang SQL package there are QueryRow and Exec for executing query. If I'm executing insertion query inside transaction, which is better to be used in term of performance?
err = tx.QueryRow(query, params).Scan(&id)
vs
result, err = tx.Exec(query, params)
Upvotes: 9
Views: 8449
Reputation: 460
Generally for reading 1 row use QueryRow()
err := tx.QueryRow(`Select col from t where col=$1`, "val").Scan(&colholder)
For manipulating data via UPDATE
, DELETE
, INSERT
etc. Use Exec
result, err := tx.Exec(`Delete from t where col=$1`, "val")
As you can see there is nothing to scan in Exec
because that is execution and not query.
However no one is stopping you from QueryRow
for Exec
operation, or vice versa but it will not be intended purpose. You might lose under the hood optimization for each type of operation.
Also if you use QueryRow
for Exec
, you will get sql.ErrNoRows
error because there is no row to return in UPDATE
, INSERT
or DELETE
.
Similarly you will not be able to get value from Exec
as it returns response which can not be .Scan
ned, if you use query operation in Exec
.
However there are cases for using QueryRow
for Exec
operations
err := tx.QueryRow(`Delete from t where col=$1 returning id`, "val").Scan(&deletedID)
You just decide if you want a return value from sql operation, use QueryRow
else use Exec
.
In your case if you want some data back like id after insert operation use QueryRow
, otherwise Exec
suits just fine.
Upvotes: 17
Reputation: 22117
If you're inserting a single row use QueryRow
- it is designed for, at most, one row update.
If you are performing multi-command updates/queries with multiple results, use Exec
. The row results from Exec
need to be closed after row iteration has completed.
So for ease of use & if you know you're only manipulating one row, go with QueryRow
.
Upvotes: 4