go-sqlite3-hak5/_example/simple/simple.go

110 lines
1.8 KiB
Go
Raw Normal View History

2011-11-11 12:38:32 +00:00
package main
import (
2012-01-20 16:44:56 +00:00
"database/sql"
2011-11-11 12:38:32 +00:00
"fmt"
_ "github.com/mattn/go-sqlite3"
2013-08-23 00:58:17 +00:00
"log"
2011-11-11 12:38:32 +00:00
"os"
)
func main() {
os.Remove("./foo.db")
db, err := sql.Open("sqlite3", "./foo.db")
if err != nil {
2013-08-23 00:58:17 +00:00
log.Fatal(err)
2011-11-11 12:38:32 +00:00
}
defer db.Close()
2011-11-11 12:38:32 +00:00
sqlStmt := `
2013-09-09 01:44:44 +00:00
create table foo (id integer not null primary key, name text);
delete from foo;
`
_, err = db.Exec(sqlStmt)
2013-09-09 01:44:44 +00:00
if err != nil {
log.Printf("%q: %s\n", err, sqlStmt)
2013-09-09 01:44:44 +00:00
return
2011-11-11 12:38:32 +00:00
}
2011-11-12 18:20:52 +00:00
tx, err := db.Begin()
if err != nil {
2013-08-23 00:58:17 +00:00
log.Fatal(err)
2011-11-12 18:20:52 +00:00
}
stmt, err := tx.Prepare("insert into foo(id, name) values(?, ?)")
2011-11-11 12:38:32 +00:00
if err != nil {
2013-08-23 00:58:17 +00:00
log.Fatal(err)
2011-11-11 12:38:32 +00:00
}
defer stmt.Close()
for i := 0; i < 100; i++ {
_, err = stmt.Exec(i, fmt.Sprintf("こんにちは世界%03d", i))
2011-11-11 12:38:32 +00:00
if err != nil {
2013-08-23 00:58:17 +00:00
log.Fatal(err)
2011-11-11 12:38:32 +00:00
}
}
err = tx.Commit()
if err != nil {
log.Fatal(err)
}
2011-11-11 12:38:32 +00:00
rows, err := db.Query("select id, name from foo")
if err != nil {
2013-08-23 00:58:17 +00:00
log.Fatal(err)
2011-11-11 12:38:32 +00:00
}
defer rows.Close()
for rows.Next() {
var id int
var name string
err = rows.Scan(&id, &name)
if err != nil {
log.Fatal(err)
}
2012-12-07 11:36:57 +00:00
fmt.Println(id, name)
2011-11-11 12:38:32 +00:00
}
err = rows.Err()
if err != nil {
log.Fatal(err)
}
stmt, err = db.Prepare("select name from foo where id = ?")
if err != nil {
2013-08-23 00:58:17 +00:00
log.Fatal(err)
}
defer stmt.Close()
var name string
err = stmt.QueryRow("3").Scan(&name)
if err != nil {
2013-08-23 00:58:17 +00:00
log.Fatal(err)
}
2012-12-07 11:36:57 +00:00
fmt.Println(name)
2012-12-26 00:53:22 +00:00
_, err = db.Exec("delete from foo")
if err != nil {
2013-08-23 00:58:17 +00:00
log.Fatal(err)
2012-12-26 00:53:22 +00:00
}
_, err = db.Exec("insert into foo(id, name) values(1, 'foo'), (2, 'bar'), (3, 'baz')")
if err != nil {
2013-08-23 00:58:17 +00:00
log.Fatal(err)
2012-12-26 00:53:22 +00:00
}
rows, err = db.Query("select id, name from foo")
if err != nil {
2013-08-23 00:58:17 +00:00
log.Fatal(err)
2012-12-26 00:53:22 +00:00
}
defer rows.Close()
for rows.Next() {
var id int
var name string
err = rows.Scan(&id, &name)
if err != nil {
log.Fatal(err)
}
2012-12-26 00:53:22 +00:00
fmt.Println(id, name)
}
err = rows.Err()
if err != nil {
log.Fatal(err)
}
2011-11-11 12:38:32 +00:00
}