l2.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package main
  2. import (
  3. "fmt"
  4. "bufio"
  5. "strings"
  6. "os"
  7. "database/sql"
  8. _ "github.com/mattn/go-sqlite3"
  9. )
  10. func add(text string, govno string) {
  11. db, err := sql.Open("sqlite3", "./base.db")
  12. if err != nil { panic(err) }
  13. defer db.Close()
  14. sqlStmt := `CREATE TABLE IF NOT EXISTS l2 (id INTEGER NOT NULL PRIMARY KEY, name TEXT, govno TEXT)`
  15. _, err = db.Exec(sqlStmt)
  16. if err != nil {panic(err)}
  17. _, err = db.Exec("INSERT INTO l2 (name, govno) VALUES(?, ?)", text, govno)
  18. if err != nil { panic(err) }
  19. }
  20. func view() {
  21. db, err := sql.Open("sqlite3", "./base.db")
  22. if err != nil {panic(err)}
  23. defer db.Close()
  24. rows, err := db.Query("SELECT id, name, govno FROM l2")
  25. if err != nil {panic(err)}
  26. defer rows.Close()
  27. for rows.Next() {
  28. var id int
  29. var name string
  30. var govno string
  31. rows.Scan(&id, &name, &govno)
  32. StringView := fmt.Sprintf("ID %d, Name %s, Thought %s\n", id, name, govno)
  33. fmt.Printf("%s", StringView)
  34. }
  35. }
  36. func DeleteByID(id string) {
  37. db, err := sql.Open("sqlite3", "./base.db")
  38. if err != nil {panic(err)}
  39. _, err = db.Exec("DELETE FROM l2 WHERE id = ?", id)
  40. if err != nil {panic(err)}
  41. fmt.Printf("delete by id %s\n", id)
  42. }
  43. func main() {
  44. scan := bufio.NewScanner(os.Stdin)
  45. for {
  46. fmt.Printf("1) Added in DB\n2) View all DB\n3) Delete by index\n4) Exit\n")
  47. fmt.Printf("Your choise(1/2/3/4) ")
  48. var choise int
  49. fmt.Scan(&choise)
  50. if choise == 1 {
  51. fmt.Printf("Your name ")
  52. scan.Scan()
  53. name := scan.Text()
  54. fmt.Printf("enter the thought ")
  55. scan.Scan()
  56. thought := strings.TrimSpace(scan.Text())
  57. add(name, thought)
  58. fmt.Printf("Added %s and %s\n", name, thought)
  59. } else if choise == 2 {
  60. fmt.Println("------------------------")
  61. view()
  62. fmt.Println("------------------------")
  63. } else if choise == 4 {
  64. return
  65. } else if choise == 3 {
  66. fmt.Printf("ID ")
  67. scan.Scan()
  68. id := scan.Text()
  69. DeleteByID(id)
  70. } else {
  71. fmt.Printf("Incorrect number\n ")
  72. }
  73. }
  74. }