TheMathemagicians/sevenkeys/main.go

100 lines
2.0 KiB
Go
Raw Normal View History

2024-04-04 13:55:12 +00:00
package main
import (
"database/sql"
"fmt"
"log"
"github.com/go-sql-driver/mysql"
)
type Product struct {
Name string
Price float64
Available bool
}
var db *sql.DB
func main() {
connectionConfig := mysql.Config{
User: "root",
Passwd: "o7MS6CIn660jIApSP",
Net: "tcp",
Addr: "127.0.0.1:3306",
DBName: "goql",
AllowNativePasswords: true,
}
var err error
db, err := sql.Open("mysql", connectionConfig.FormatDSN())
defer db.Close()
if err != nil {
log.Fatal(err)
}
if err = db.Ping(); err != nil {
log.Fatal(err)
}
fmt.Println("Connected!")
createProductTable(db)
insertProduct(db, Product{Name: "Book 1", Price: 15.95, Available: true})
insertProduct(db, Product{Name: "Book 2", Price: 15.95, Available: true})
insertProduct(db, Product{Name: "Book 3", Price: 15.95, Available: true})
insertProduct(db, Product{Name: "Book 4", Price: 15.95, Available: true})
insertProduct(db, Product{Name: "Book 5", Price: 15.95, Available: true})
products := getAllProducts(db)
fmt.Println(products)
}
func createProductTable(db *sql.DB) {
query := `CREATE TABLE IF NOT EXISTS Product (
Id SERIAL PRIMARY KEY,
Name VARCHAR(100) NOT NULL,
Price NUMERIC(6,2) NOT NULL,
Available BOOLEAN,
Created TIMESTAMP DEFAULT NOW()
)`
_, err := db.Exec(query)
if err != nil {
log.Fatal(err)
}
}
func insertProduct(db *sql.DB, product Product) {
query := "INSERT INTO Product (Name, Price, Available) VALUES ($1, $2, $3);"
db.QueryRow(query, product.Name, product.Price, product.Available)
}
func getAllProducts(db *sql.DB) []Product {
products := []Product{}
rows, err := db.Query("SELECT Name, Price, Available FROM Product;")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
var name string
var price float64
var available bool
for rows.Next() {
err := rows.Scan(&name, &price, &available)
if err != nil {
log.Fatal(err)
}
products = append(products, Product{name, price, available})
}
return products
}