Add main.go

This commit is contained in:
The Magician 2024-04-12 09:59:09 +01:00
parent ada6a95721
commit b6f08c2c1b
1 changed files with 19 additions and 8 deletions

View File

@ -68,10 +68,23 @@ func createProductTable(db *sql.DB) {
} }
} }
func insertProduct(db *sql.DB, product Product) { func insertProduct(db *sql.DB, product Product) int64 {
query := "INSERT INTO Product (Name, Price, Available) VALUES ($1, $2, $3);" query := "INSERT INTO Product (Name, Price, Available) VALUES (?, ?, ?);"
db.QueryRow(query, product.Name, product.Price, product.Available) insert, err := db.Prepare(query)
defer insert.Close()
if err != nil {
log.Fatal(err)
}
result, err := insert.Exec(product.Name, product.Price, product.Available)
rowsAffected, _ := result.RowsAffected()
if err != nil || rowsAffected != 1 {
log.Fatal(err)
}
insertedRowId, _ := result.LastInsertId()
return insertedRowId
} }
func getAllProducts(db *sql.DB) []Product { func getAllProducts(db *sql.DB) []Product {
@ -83,16 +96,14 @@ func getAllProducts(db *sql.DB) []Product {
} }
defer rows.Close() defer rows.Close()
var name string var product Product
var price float64
var available bool
for rows.Next() { for rows.Next() {
err := rows.Scan(&name, &price, &available) err := rows.Scan(&product.Name, &product.Price, &product.Available)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
products = append(products, Product{name, price, available}) products = append(products, product)
} }
return products return products