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)
}
}