2011-11-11 16:38:32 +04:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2012-01-20 20:44:56 +04:00
|
|
|
"database/sql"
|
2011-11-11 16:38:32 +04:00
|
|
|
"fmt"
|
2012-10-29 09:28:49 +04:00
|
|
|
_ "github.com/mattn/go-sqlite3"
|
2011-11-11 16:38:32 +04:00
|
|
|
"os"
|
|
|
|
)
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
os.Remove("./foo.db")
|
|
|
|
|
|
|
|
db, err := sql.Open("sqlite3", "./foo.db")
|
|
|
|
if err != nil {
|
|
|
|
fmt.Println(err)
|
|
|
|
return
|
|
|
|
}
|
2012-02-23 09:30:50 +04:00
|
|
|
defer db.Close()
|
2011-11-11 16:38:32 +04:00
|
|
|
|
|
|
|
sqls := []string{
|
|
|
|
"create table foo (id integer not null primary key, name text)",
|
|
|
|
"delete from foo",
|
|
|
|
}
|
|
|
|
for _, sql := range sqls {
|
|
|
|
_, err = db.Exec(sql)
|
|
|
|
if err != nil {
|
|
|
|
fmt.Printf("%q: %s\n", err, sql)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2011-11-12 22:20:52 +04:00
|
|
|
tx, err := db.Begin()
|
|
|
|
if err != nil {
|
|
|
|
fmt.Println(err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
stmt, err := tx.Prepare("insert into foo(id, name) values(?, ?)")
|
2011-11-11 16:38:32 +04:00
|
|
|
if err != nil {
|
|
|
|
fmt.Println(err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
defer stmt.Close()
|
|
|
|
for i := 0; i < 100; i++ {
|
|
|
|
_, err = stmt.Exec(i, fmt.Sprintf("こんにちわ世界%03d", i))
|
|
|
|
if err != nil {
|
|
|
|
fmt.Println(err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
2011-11-12 22:20:52 +04:00
|
|
|
tx.Commit()
|
2011-11-11 16:38:32 +04:00
|
|
|
|
|
|
|
rows, err := db.Query("select id, name from foo")
|
|
|
|
if err != nil {
|
|
|
|
fmt.Println(err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
defer rows.Close()
|
|
|
|
for rows.Next() {
|
|
|
|
var id int
|
|
|
|
var name string
|
|
|
|
rows.Scan(&id, &name)
|
|
|
|
println(id, name)
|
|
|
|
}
|
2012-02-23 09:30:50 +04:00
|
|
|
rows.Close()
|
|
|
|
|
|
|
|
stmt, err = db.Prepare("select name from foo where id = ?")
|
|
|
|
if err != nil {
|
|
|
|
fmt.Println(err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
defer stmt.Close()
|
|
|
|
var name string
|
|
|
|
err = stmt.QueryRow("3").Scan(&name)
|
|
|
|
if err != nil {
|
|
|
|
fmt.Println(err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
println(name)
|
2011-11-11 16:38:32 +04:00
|
|
|
}
|