2 回答
TA贡献1874条经验 获得超12个赞
您为每一行设置相同的结构变量,这就是为什么您只获取最后一行信息。
用于results := []NewsPaper{}创建空切片并为每一行创建新结构。这应该可行,我添加了一些评论。
rows, err := db.Query(`SELECT title, language, ranking, slug, search_term, logo_url FROM public.news_newspaper`)
if err != nil {
log.Println(err)
}
results := []NewsPaper{} // creating empty slice
defer rows.Close()
for rows.Next() {
newspaper := NewsPaper{} // creating new struct for every row
err = rows.Scan(&newspaper.title, &newspaper.language, &newspaper.ranking, &newspaper.slug, &newspaper.search_term, &newspaper.logo_url)
if err != nil {
log.Println(err)
}
results = append(results, newspaper) // add new row information
}
fmt.Println(results) // printing result
TA贡献2039条经验 获得超8个赞
基本 CRUD 的另一种方法
import (
"github.com/jmoiron/sqlx"
"context"
)
type NewsPaper struct {
Language string `json:"language" db:"language"`
LogoURL string `json:"logo_url" db:"logo_url"`
Slug string `json:"slug" db:"slug"`
Ranking string `json:"ranking" db:"ranking"`
Title string `json:"title" db:"title"`
SearchTerm string `json:"search_term" db:"search_term"`
}
type NewsPaperRepository interface {
List(ctx context.Context) ([]NewsPaper, error)
}
type newsPaperRepository struct {
db *sqlx.DB
}
func (r *newsPaperRepository) List(ctx context.Context) ([]NewsPaper, error) {
const selectQuery = `SELECT title, language, ranking, slug, search_term, logo_url FROM public.news_newspaper`
var newsPapers []NewsPaper
if err := r.db.SelectContext(ctx, &newsPapers, selectQuery); err != nil {
return nil, fmt.Errorf("news paper repository/problem while trying to retrieve news papers from database: %w", err)
}
return newsPapers, nil
}
- 2 回答
- 0 关注
- 169 浏览
添加回答
举报
