111 lines
2.3 KiB
Go
111 lines
2.3 KiB
Go
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) int64 {
|
|
query := "INSERT INTO Product (Name, Price, Available) VALUES (?, ?, ?);"
|
|
|
|
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 {
|
|
products := []Product{}
|
|
|
|
rows, err := db.Query("SELECT Name, Price, Available FROM Product;")
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
defer rows.Close()
|
|
|
|
var product Product
|
|
for rows.Next() {
|
|
err := rows.Scan(&product.Name, &product.Price, &product.Available)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
products = append(products, product)
|
|
}
|
|
|
|
return products
|
|
}
|