Add main.go
This commit is contained in:
parent
ada6a95721
commit
b6f08c2c1b
|
@ -68,10 +68,23 @@ func createProductTable(db *sql.DB) {
|
|||
}
|
||||
}
|
||||
|
||||
func insertProduct(db *sql.DB, product Product) {
|
||||
query := "INSERT INTO Product (Name, Price, Available) VALUES ($1, $2, $3);"
|
||||
func insertProduct(db *sql.DB, product Product) int64 {
|
||||
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 {
|
||||
|
@ -83,16 +96,14 @@ func getAllProducts(db *sql.DB) []Product {
|
|||
}
|
||||
defer rows.Close()
|
||||
|
||||
var name string
|
||||
var price float64
|
||||
var available bool
|
||||
var product Product
|
||||
for rows.Next() {
|
||||
err := rows.Scan(&name, &price, &available)
|
||||
err := rows.Scan(&product.Name, &product.Price, &product.Available)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
products = append(products, Product{name, price, available})
|
||||
products = append(products, product)
|
||||
}
|
||||
|
||||
return products
|
||||
|
|
Loading…
Reference in New Issue