如何打印查询产生的多个字段? [英] How can I print more than one fields resulting from a query?
问题描述
我试图学习如何在数据库/ sql 包/rel =nofollow> go-sql-driver 。我写了下面这个简单的程序,它可以工作,但我无法弄清楚如何打印多个字段。
$ b 数据库 wiki1
code>有三个字段, 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)
返回
}
推迟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 {
)
为rows.Next(){
var title,body string
if err:= rows.Scan(&标题); err!= nil {
fmt.Println(err)
}
fmt.Printf(%s\\\
,title)
}
如果err:= rows.Err(); err!= nil {
fmt.Println(err)
}
}
标题
,而不是仅仅阅读标题
,首先更改语句。 更改
st,err:= db.Prepare(SELECT title FROM page WHERE title =?)
到
st,err:= db.Prepare(SELECT body,title FROM page WHERE title =?)
然后改变读数。更改
var标题,正文字符串
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 \\\
body:%s\\\
,title,body)
你会发现更多关于使用数据库/ sql进行查询的细节,请阅读相关问题。
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)
}
}
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.
这篇关于如何打印查询产生的多个字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!