https://github.com/mattn/go-sqlite3

    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. err = tx.Commit()
    41. if err != nil {
    42. log.Fatal(err)
    43. }
    44. rows, err := db.Query("select id, name from foo")
    45. if err != nil {
    46. log.Fatal(err)
    47. }
    48. defer rows.Close()
    49. for rows.Next() {
    50. var id int
    51. var name string
    52. err = rows.Scan(&id, &name)
    53. if err != nil {
    54. log.Fatal(err)
    55. }
    56. fmt.Println(id, name)
    57. }
    58. err = rows.Err()
    59. if err != nil {
    60. log.Fatal(err)
    61. }
    62. stmt, err = db.Prepare("select name from foo where id = ?")
    63. if err != nil {
    64. log.Fatal(err)
    65. }
    66. defer stmt.Close()
    67. var name string
    68. err = stmt.QueryRow("3").Scan(&name)
    69. if err != nil {
    70. log.Fatal(err)
    71. }
    72. fmt.Println(name)
    73. _, err = db.Exec("delete from foo")
    74. if err != nil {
    75. log.Fatal(err)
    76. }
    77. _, err = db.Exec("insert into foo(id, name) values(1, 'foo'), (2, 'bar'), (3, 'baz')")
    78. if err != nil {
    79. log.Fatal(err)
    80. }
    81. rows, err = db.Query("select id, name from foo")
    82. if err != nil {
    83. log.Fatal(err)
    84. }
    85. defer rows.Close()
    86. for rows.Next() {
    87. var id int
    88. var name string
    89. err = rows.Scan(&id, &name)
    90. if err != nil {
    91. log.Fatal(err)
    92. }
    93. fmt.Println(id, name)
    94. }
    95. err = rows.Err()
    96. if err != nil {
    97. log.Fatal(err)
    98. }
    99. }