added database in go/l19/l1.go

This commit is contained in:
hhu67 2026-07-02 18:20:12 +03:00
parent 521a1988a8
commit 00a68fc404
4 changed files with 54 additions and 6 deletions

1
.gitignore vendored
View file

@ -2,3 +2,4 @@
.env .env
.idea .idea
go_build_my_app go_build_my_app
*.db

View file

@ -5,6 +5,8 @@ import (
"net/http" "net/http"
"encoding/json" "encoding/json"
"strings" "strings"
"database/sql"
_ "github.com/mattn/go-sqlite3"
) )
type User struct{ type User struct{
@ -53,9 +55,54 @@ func handle(w http.ResponseWriter, r *http.Request) {
func WatchChanell() { func WatchChanell() {
for u := range setChan { for u := range setChan {
JsonData, err := json.Marshal(u) db, err := sql.Open("sqlite3", "./base.db")
if err != nil { continue } if err != nil {
fmt.Println(string(JsonData)) panic(err)
}
defer db.Close()
sqlStmt := `CREATE TABLE IF NOT EXISTS l1 (
id INTEGER NOT NULL PRIMARY KEY,
age INTEGER DEFAULT 0,
name TEXT,
email TEXT,
alive INTEGER NOT NULL DEFAULT 0 CHECK (alive IN (0, 1))
); `
_, err = db.Exec(sqlStmt)
if err != nil {
panic(err)
}
var Alive int
if u.Alive {
Alive = 1
} else {
Alive = 0
}
_, err = db.Exec("INSERT INTO l1 (age, name, email, alive) VALUES(?, ?, ?, ?)", u.Age, u.Name, u.Email, Alive)
if err != nil {
panic(err)
}
defer db.Close()
rows, err := db.Query("SELECT id, age, name, email, alive FROM l1")
if err != nil {
panic(err)
}
for rows.Next() {
var id int
var age int
var name string
var email string
var alive int
var boolAlive bool
rows.Scan(&id, &age, &name, &email, &alive)
if alive == 1 {
boolAlive = true
}
if alive == 0 {
boolAlive = false
}
StrAnswer := fmt.Sprintf("ID %d, Age %d, Name %s, Email %s, Alive %t\n", id, age, name, email, boolAlive)
fmt.Printf("%s", StrAnswer)
}
} }
} }

Binary file not shown.

View file

@ -20,16 +20,16 @@ func main() {
} }
defer db.Close() defer db.Close()
sqlStmt := `CREATE TABLE IF NOT EXISTS users (id INTEGER NOT NULL PRIMARY KEY, name TEXT, time TEXT);` sqlStmt := `CREATE TABLE IF NOT EXISTS l1 (id INTEGER NOT NULL PRIMARY KEY, name TEXT, time TEXT);`
_, err = db.Exec(sqlStmt) _, err = db.Exec(sqlStmt)
if err != nil { if err != nil {
panic(err) panic(err)
} }
_, err = db.Exec("INSERT INTO users(name, time) VALUES(?, ?)", username, userTime) _, err = db.Exec("INSERT INTO l1 (name, time) VALUES(?, ?)", username, userTime)
if err != nil { if err != nil {
panic(err) panic(err)
} }
rows, err := db.Query("SELECT id, name, time FROM users") rows, err := db.Query("SELECT id, name, time FROM l1")
if err != nil { if err != nil {
panic(err) panic(err)
} }