Skip to content
Advertisement

Go sql return multiple row from Scan

I am using Postgresql database . Here is my code block where I want to return multiple rows:

type NewsPaper struct {
    language string
    logo_url string
    slug string
    ranking string
    title string
    search_term string
}

func GetNewsPapers()  []byte{
    db := GetDB()
    newspaper := NewsPaper{}
    var json = jsoniter.ConfigCompatibleWithStandardLibrary

    rows, err := db.Query(`SELECT title, language, ranking, slug, search_term, logo_url FROM public.news_newspaper`)
    if err != nil {
        log.Println(err)
    }

    defer rows.Close()
    //results := []NewsPaper  // error : type []NewsPaper is not an expression
    for rows.Next() {

        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)
    }
    fmt.Println(newspaper)  // printing last row
    err = rows.Err()
    if err != nil {
        panic(err)
    }
    values, _ := json.Marshal(newspaper)
    //fmt.Println(values)

    return values
}

Problem is its returning last row from the table. I also tried to store result in array, but I am not succeed.

Advertisement

Answer

You are setting same struct variable for every row that’s why you are getting last row info only.

Use results := []NewsPaper{} for create empty slice and create new struct for every row. This should work, I added some comments.

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
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement