Zeynel
Zeynel

Reputation: 13525

How can I print more than one fields resulting from a query?

I am trying to learn how to use the database/sql package with go-sql-driver. I wrote the following simple program and it works, but I could not figure out how to print more than one fields.

The database wiki1 has three fields, id, title and body. I query for "title1" which is one of the values but I want to print the values for "title" and "body". How do I this?

package main

import (
    "database/sql"
    "fmt"
    _ "github.com/go-sql-driver/mysql"
)

func main() {


    db, err := sql.Open("mysql", "root:Password1@/wiki1")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer db.Close()

    st, err := db.Prepare("SELECT title FROM page WHERE title=?")
    if err != nil {
        fmt.Println(err)
    }
    rows, err := st.Query("title1")
    if err != nil {
        fmt.Println(err)
    }

    for rows.Next() {
        var title, body string
        if err := rows.Scan(&title); err != nil {
            fmt.Println(err)
        }

        fmt.Printf("%s\n", title)
    }
    if err := rows.Err(); err != nil {
        fmt.Println(err)
    }
}

Upvotes: 0

Views: 129

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382284

To read the body and the title instead of just the title, first change the statement.

Change

st, err := db.Prepare("SELECT title FROM page WHERE title=?")

to

st, err := db.Prepare("SELECT body, title FROM page WHERE title=?")

Then change the reading. Change

    var title, body string
    if err := rows.Scan(&title); err != nil {
        fmt.Println(err)
    }

to

    var title, body string
    if err := rows.Scan(&body, &title); err != nil {
        fmt.Println(err)
    }

This reads both columns.

To print the fields, you can do

fmt.Printf("title: %s\nbody: %s\n", title, body)

You'll find more details regarding querying using database/sql, read this related question.

Upvotes: 2

Related Questions