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

1 回答 1

2

要阅读bodyandtitle而不仅仅是title,首先更改语句。

改变

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

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

然后改变读数。改变

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

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

这将读取两列。

要打印字段,您可以执行

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

您将找到有关使用 database/sql 查询的更多详细信息,请阅读此相关问题

于 2013-07-20T15:32:19.707 回答