0

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)
    }
}
Zeynel
  • 13,145
  • 31
  • 100
  • 145

1 Answers1

2

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.

Community
  • 1
  • 1
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • Thank you, @dystroy! I noticed also that the order of column names in `SELECT` must match the order of columns in the database. – Zeynel Jul 20 '13 at 17:38
  • 1
    No, the order of column in the select doesn't have to match the one of the database, normally. But the order in the select must match the order of the `scan`. – Denys Séguret Jul 20 '13 at 18:21