英文:
How can I print more than one fields resulting from a query?
问题
我正在尝试学习如何使用database/sql
包和go-sql-driver。我编写了以下简单的程序,它可以工作,但是我无法弄清楚如何打印多个字段。
数据库wiki1
有三个字段,id
,title
和body
。我查询了一个值为"title1"的记录,但我想打印"title"和"body"的值。我应该如何做到这一点?
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)
}
}
英文:
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)
}
}
答案1
得分: 2
要读取body
和title
而不仅仅是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进行查询的更多详细信息,请阅读此相关问题。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论