CodeBlanks Logo Icon CodeBlanks

Query and Exec

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

main.go
package main

import (
    "database/sql"
    "errors"
    "fmt"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
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

Question
for rows.____() {
    rows.Scan(&id)
}
Answer
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

All lessons in Advanced