Query and Exec
- Go course
- Advanced
- Lesson 27/68
- 4 min
Learn to read rows with Query and modify with Exec.
Query and Exec
Use Query for queries that return rows (SELECT), or QueryRow for a single row; use Exec for those that don't (INSERT, UPDATE, DELETE).
rows, err := db.Query("SELECT id, ad FROM urunler")
if err != nil { return err }
defer rows.Close()
for rows.Next() {
var id int
var ad string
if err := rows.Scan(&id, &ad); err != nil { return err }
}
return rows.Err()The Exec result
Exec returns a sql.Result. RowsAffected() tells how many rows changed and LastInsertId() (on drivers that support it) the new row's ID:
res, err := db.Exec("UPDATE urunler SET stok = stok - 1 WHERE id = ?", 7)
n, _ := res.RowsAffected()
fmt.Println(n, "satır güncellendi")For a single row, db.QueryRow(...).Scan(&x) is the short way; with no row it returns sql.ErrNoRows.
Practice No-rows check
Try the sql.ErrNoRows check with errors.Is: declare err := sql.ErrNoRows and print errors.Is(err, sql.ErrNoRows).
Starter code
package main
import (
"database/sql"
"errors"
"fmt"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"database/sql"
"errors"
"fmt"
)
func main() {
err := sql.ErrNoRows
fmt.Println(errors.Is(err, sql.ErrNoRows))
}Expected output
true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens if <code>rows.Close()</code> is forgotten?
- The query runs twice
- It has no effect
- The data is deleted
- The connection isn't returned to the pool, which can run dry Correct answer
Explanation: Open Rows hold a connection; if you don't finish the loop or call Close, connections leak.
2 Read the rows
for rows.____() {
rows.Scan(&id)
}
for rows.Next() {
rows.Scan(&id)
}
Explanation: rows.Next moves to the next row and returns false when none are left.
3 Which method?
| Term | Meaning |
|---|---|
SELECT many rows |
Query |
SELECT one row |
QueryRow |
INSERT / UPDATE |
Exec |
No-rows error |
sql.ErrNoRows |