This commit is contained in:
mattn 2013-08-23 09:58:17 +09:00
parent f6dadd82d8
commit 6671b69503
1 changed files with 12 additions and 23 deletions

View File

@ -4,6 +4,7 @@ import (
"database/sql" "database/sql"
"fmt" "fmt"
_ "github.com/mattn/go-sqlite3" _ "github.com/mattn/go-sqlite3"
"log"
"os" "os"
) )
@ -12,8 +13,7 @@ func main() {
db, err := sql.Open("sqlite3", "./foo.db") db, err := sql.Open("sqlite3", "./foo.db")
if err != nil { if err != nil {
fmt.Println(err) log.Fatal(err)
return
} }
defer db.Close() defer db.Close()
@ -24,35 +24,31 @@ func main() {
for _, sql := range sqls { for _, sql := range sqls {
_, err = db.Exec(sql) _, err = db.Exec(sql)
if err != nil { if err != nil {
fmt.Printf("%q: %s\n", err, sql) log.Printf("%q: %s\n", err, sql)
return return
} }
} }
tx, err := db.Begin() tx, err := db.Begin()
if err != nil { if err != nil {
fmt.Println(err) log.Fatal(err)
return
} }
stmt, err := tx.Prepare("insert into foo(id, name) values(?, ?)") stmt, err := tx.Prepare("insert into foo(id, name) values(?, ?)")
if err != nil { if err != nil {
fmt.Println(err) log.Fatal(err)
return
} }
defer stmt.Close() defer stmt.Close()
for i := 0; i < 100; i++ { for i := 0; i < 100; i++ {
_, err = stmt.Exec(i, fmt.Sprintf("こんにちわ世界%03d", i)) _, err = stmt.Exec(i, fmt.Sprintf("こんにちわ世界%03d", i))
if err != nil { if err != nil {
fmt.Println(err) log.Fatal(err)
return
} }
} }
tx.Commit() tx.Commit()
rows, err := db.Query("select id, name from foo") rows, err := db.Query("select id, name from foo")
if err != nil { if err != nil {
fmt.Println(err) log.Fatal(err)
return
} }
defer rows.Close() defer rows.Close()
for rows.Next() { for rows.Next() {
@ -65,34 +61,29 @@ func main() {
stmt, err = db.Prepare("select name from foo where id = ?") stmt, err = db.Prepare("select name from foo where id = ?")
if err != nil { if err != nil {
fmt.Println(err) log.Fatal(err)
return
} }
defer stmt.Close() defer stmt.Close()
var name string var name string
err = stmt.QueryRow("3").Scan(&name) err = stmt.QueryRow("3").Scan(&name)
if err != nil { if err != nil {
fmt.Println(err) log.Fatal(err)
return
} }
fmt.Println(name) fmt.Println(name)
_, err = db.Exec("delete from foo") _, err = db.Exec("delete from foo")
if err != nil { if err != nil {
fmt.Println(err) log.Fatal(err)
return
} }
_, err = db.Exec("insert into foo(id, name) values(1, 'foo'), (2, 'bar'), (3, 'baz')") _, err = db.Exec("insert into foo(id, name) values(1, 'foo'), (2, 'bar'), (3, 'baz')")
if err != nil { if err != nil {
fmt.Println(err) log.Fatal(err)
return
} }
rows, err = db.Query("select id, name from foo") rows, err = db.Query("select id, name from foo")
if err != nil { if err != nil {
fmt.Println(err) log.Fatal(err)
return
} }
defer rows.Close() defer rows.Close()
for rows.Next() { for rows.Next() {
@ -101,6 +92,4 @@ func main() {
rows.Scan(&id, &name) rows.Scan(&id, &name)
fmt.Println(id, name) fmt.Println(id, name)
} }
rows.Close()
} }