go-sqlite3/_example/simple/simple.go

110 lines
1.8 KiB
Go
Raw Normal View History

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