Difference between revisions of "PostgreSQL Examples"
Jump to navigation
Jump to search
(Created page with "https://www.enterprisedb.com/postgres-tutorials/postgresql-query-introduction-explanation-and-50-examples") |
|||
Line 1: | Line 1: | ||
https://www.enterprisedb.com/postgres-tutorials/postgresql-query-introduction-explanation-and-50-examples | https://www.enterprisedb.com/postgres-tutorials/postgresql-query-introduction-explanation-and-50-examples | ||
+ | |||
+ | |||
+ | ``` | ||
+ | func albumsByArtist(artist string) ([]Album, error) { | ||
+ | rows, err := db.Query("SELECT * FROM album WHERE artist = ?", artist) | ||
+ | if err != nil { | ||
+ | return nil, err | ||
+ | } | ||
+ | defer rows.Close() | ||
+ | |||
+ | // An album slice to hold data from returned rows. | ||
+ | var albums []Album | ||
+ | |||
+ | // Loop through rows, using Scan to assign column data to struct fields. | ||
+ | for rows.Next() { | ||
+ | var alb Album | ||
+ | if err := rows.Scan(&alb.ID, &alb.Title, &alb.Artist, | ||
+ | &alb.Price, &alb.Quantity); err != nil { | ||
+ | return albums, err | ||
+ | } | ||
+ | albums = append(albums, album) | ||
+ | } | ||
+ | if err = rows.Err(); err != nil { | ||
+ | return albums, err | ||
+ | } | ||
+ | return albums, nil | ||
+ | } | ||
+ | ``` |
Latest revision as of 17:49, 28 December 2021
func albumsByArtist(artist string) ([]Album, error) { rows, err := db.Query("SELECT * FROM album WHERE artist = ?", artist) if err != nil { return nil, err } defer rows.Close() // An album slice to hold data from returned rows. var albums []Album // Loop through rows, using Scan to assign column data to struct fields. for rows.Next() { var alb Album if err := rows.Scan(&alb.ID, &alb.Title, &alb.Artist, &alb.Price, &alb.Quantity); err != nil { return albums, err } albums = append(albums, album) } if err = rows.Err(); err != nil { return albums, err } return albums, nil }