Merge remote-tracking branch 'refs/remotes/origin/main'

This commit is contained in:
The Magician 2024-04-04 19:31:23 +01:00
commit ada6a95721
3 changed files with 111 additions and 0 deletions

8
sevenkeys/go.mod Normal file
View File

@ -0,0 +1,8 @@
module main
go 1.22.1
require (
filippo.io/edwards25519 v1.1.0 // indirect
github.com/go-sql-driver/mysql v1.8.1 // indirect
)

4
sevenkeys/go.sum Normal file
View File

@ -0,0 +1,4 @@
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=

99
sevenkeys/main.go Normal file
View File

@ -0,0 +1,99 @@
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
}