simple.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package main
  2. import (
  3. "database/sql"
  4. "fmt"
  5. _ "github.com/mattn/go-sqlite3"
  6. "log"
  7. "os"
  8. )
  9. func main() {
  10. os.Remove("./foo.db")
  11. db, err := sql.Open("sqlite3", "./foo.db")
  12. if err != nil {
  13. log.Fatal(err)
  14. }
  15. defer db.Close()
  16. sqlStmt := `
  17. create table foo (id integer not null primary key, name text);
  18. delete from foo;
  19. `
  20. _, err = db.Exec(sqlStmt)
  21. if err != nil {
  22. log.Printf("%q: %s\n", err, sqlStmt)
  23. return
  24. }
  25. tx, err := db.Begin()
  26. if err != nil {
  27. log.Fatal(err)
  28. }
  29. stmt, err := tx.Prepare("insert into foo(id, name) values(?, ?)")
  30. if err != nil {
  31. log.Fatal(err)
  32. }
  33. defer stmt.Close()
  34. for i := 0; i < 100; i++ {
  35. _, err = stmt.Exec(i, fmt.Sprintf("こんにちわ世界%03d", i))
  36. if err != nil {
  37. log.Fatal(err)
  38. }
  39. }
  40. tx.Commit()
  41. rows, err := db.Query("select id, name from foo")
  42. if err != nil {
  43. log.Fatal(err)
  44. }
  45. defer rows.Close()
  46. for rows.Next() {
  47. var id int
  48. var name string
  49. err = rows.Scan(&id, &name)
  50. if err != nil {
  51. log.Fatal(err)
  52. }
  53. fmt.Println(id, name)
  54. }
  55. err = rows.Err()
  56. if err != nil {
  57. log.Fatal(err)
  58. }
  59. stmt, err = db.Prepare("select name from foo where id = ?")
  60. if err != nil {
  61. log.Fatal(err)
  62. }
  63. defer stmt.Close()
  64. var name string
  65. err = stmt.QueryRow("3").Scan(&name)
  66. if err != nil {
  67. log.Fatal(err)
  68. }
  69. fmt.Println(name)
  70. _, err = db.Exec("delete from foo")
  71. if err != nil {
  72. log.Fatal(err)
  73. }
  74. _, err = db.Exec("insert into foo(id, name) values(1, 'foo'), (2, 'bar'), (3, 'baz')")
  75. if err != nil {
  76. log.Fatal(err)
  77. }
  78. rows, err = db.Query("select id, name from foo")
  79. if err != nil {
  80. log.Fatal(err)
  81. }
  82. defer rows.Close()
  83. for rows.Next() {
  84. var id int
  85. var name string
  86. err = rows.Scan(&id, &name)
  87. if err != nil {
  88. log.Fatal(err)
  89. }
  90. fmt.Println(id, name)
  91. }
  92. err = rows.Err()
  93. if err != nil {
  94. log.Fatal(err)
  95. }
  96. }