Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
115 lines (94 loc) · 2.45 KB
/
Copy pathmain.go
File metadata and controls
115 lines (94 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package main
import (
"database/sql"
"fmt"
_ "github.com/mattn/go-sqlite3"
)
func main() {
db, err := sql.Open("sqlite3", "./books.db")
if err != nil {
panic(err)
}
defer db.Close()
// Create books table
createBooksTable := `
CREATE TABLE IF NOT EXISTS books (
id INTEGER PRIMARY KEY AUTOINCREMENT,
TITLE TEXT,
author TEXT,
year INTEGER
);`
_, err = db.Exec(createBooksTable)
if err != nil {
panic(err)
}
fmt.Println("Books table created successfully.")
createUsersTable := `
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user TEXT NOT NULL UNIQUE,
password TEXT NOT NULL
);`
_, err = db.Exec(createUsersTable)
if err != nil {
panic(err)
}
fmt.Println("Users table created.")
// Example usage
insertBook(db, "Go Programming", "Mosun", 2024)
listsBooks(db)
updateBookTitle(db, 1, "Go Programming Updated")
deleteBook(db, 1)
addUser(db, "mosun", "1234")
loginUser(db, "mosun", "1234")
}
func insertBook(db *sql.DB, title, author string, year int) {
stmt, _ := db.Prepare("INSERT INTO books(title, author, year) VALUES (?, ?, ?)")
stmt.Exec(title, author, year)
fmt.Println("Book inserted!")
}
func listsBooks(db *sql.DB) {
rows, _ := db.Query("SELECT id, title, author, year FROM books")
defer rows.Close()
fmt.Println("Books:")
for rows.Next() {
var id, year int
var title, author string
rows.Scan(&id, &title, &author, &year)
fmt.Printf("%d: %s by %s (%d)\n", id, title, author, year)
}
}
func updateBookTitle(db *sql.DB, id int, newTitle string) {
stmt, _ := db.Prepare("UPDATE books SET title = ? WHERE id = ?")
stmt.Exec(newTitle, id)
fmt.Println("Book updated.")
}
func deleteBook(db *sql.DB, id int) {
stmt, _ := db.Prepare("DELETE FROM books WHERE id = ?")
stmt.Exec(id)
fmt.Println("Book deleted.")
}
func addUser(db *sql.DB, username, password string) {
stmt, _ := db.Prepare("INSERT INTO users(username, password) VALUES (?, ?)")
_, err := stmt.Exec(username, password)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("User added.")
}
}
func loginUser(db *sql.DB, username, password string) bool {
var storePassword string
row := db.QueryRow("SELECT password FROM users WHERE username = ?", username)
err := row.Scan(&storePassword)
if err != nil {
fmt.Println("Login failed: User not found.")
return false
}
if storePassword == password {
fmt.Println("Login successful!")
return true
}
fmt.Println("Login failed: Incorrect password.")
return false
}