我有此代码:
func GetAll(c *gin.Context) {
var veiculos model.Veiculo
rows, err := db.Query("SELECT * FROM vei_veiculo")
if err != nil {
fmt.Println("[GetAll] erro ao abrir o query db inteiro")
}
defer rows.Close()
for rows.Next() {
err := rows.Scan(&veiculos)
if err != nil {
fmt.Println("[GetAll] erro ao scanear uma linha'")
}
}
fmt.Println(veiculos)}
我的结构名称是model.Veiculo,我想将其全部打印一次。扫描查询行时似乎出现错误。我做错了什么?
答案 0 :(得分:1)
假设您正在使用database/sql
,则函数签名为func (rs *Rows) Scan(dest ...interface{}) error
。
您需要对结构的每个成员进行扫描,类似于:
err := rows.Scan(&veiculos.ID, &veiculos.Name, &veiculos.Description)
答案 1 :(得分:0)
要将每一行扫描到自己的结构,我建议采用类似的方法:
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/go-sql-driver/mysql"
)
type Person struct {
FirstName string
LastName string
Email string
}
func main() {
db, err := sql.Open("mysql", "dsn...")
if err != nil {
log.Fatalln(err)
}
defer db.Close()
people := []Person{}
rows, err := db.Query("SELECT * FROM people")
if err != nil {
log.Fatalln(err)
}
for rows.Next() {
person := Person{}
if err := rows.Scan(&person.FirstName, &person.LastName, &person.Email); err != nil {
log.Fatalln(err)
}
people = append(people, person)
}
fmt.Printf("%+v\n", people)
}
或者,https://github.com/jmoiron/sqlx库作为将SQL查询数据编组到结构的解决方案之一而存在。我个人更喜欢这种方法,因为它的行为更像是Unmarshal
函数:
package main
import (
"fmt"
"log"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
)
type Person struct {
FirstName string `db:"first_name"`
LastName string `db:"last_name"`
Email string `db:"email"`
}
func main() {
db, err := sqlx.Connect("mysql", "dsn...")
if err != nil {
log.Fatalln(err)
}
people := []Person{}
if err := db.Select(&people, "SELECT * FROM people"); err != nil {
log.Fataln(err)
}
fmt.Printf("%+v\n", people)
}
采用以下两种方法之一,即可轻松使用json.Marshal
people
变量和中提琴的方法!
祝你好运!