hakeの日記

Windows環境でプログラミングの勉強をしています。

Go言語 - データベースを使用する - sqlite3

go言語でsqlite3を使用してみる。
Windows 64bitで下記の方法だと、コンパイル時に何故かgccを要求されます。コンパイルに通常よりも時間がかかるのでgccを利用した何かを行っている? なお作成されたexeファイルの実行はgcc環境がなくてもOKでした。

入手先

データベースの作成とデータの追加

package main

import (
	"os"
	"database/sql"
	_ "github.com/mattn/go-sqlite3"
)

func main(){
	
	var dbfile string = "./test.db"

	os.Remove( dbfile )

//	db, err := sql.Open("sqlite3", ":memory:")
	db, err := sql.Open("sqlite3", dbfile)
	if err != nil { panic(err) }

	_, err = db.Exec( `CREATE TABLE "world" ("id" INTEGER PRIMARY KEY AUTOINCREMENT, "country" VARCHAR(255), "capital" VARCHAR(255))` )
	if err != nil { panic(err) }

	_, err = db.Exec(
			`INSERT INTO "world" ("country", "capital") VALUES (?, ?) `,
			 "日本",
			 "東京",
			)
	if err != nil { panic(err) }


	stmt, err := db.Prepare( `INSERT INTO "world" ("country", "capital") VALUES (?, ?) ` )
	if err != nil { panic(err) }

	if _, err = stmt.Exec("アメリカ", "ワシントンD.C."); err != nil { panic(err) }
	if _, err = stmt.Exec("ロシア", "モスクワ"); err != nil { panic(err) }
	if _, err = stmt.Exec("イギリス", "ロンドン"); err != nil { panic(err) }
	if _, err = stmt.Exec("オーストラリア", "シドニー"); err != nil { panic(err) }
	stmt.Close()

	db.Close()
}
コマンドプロンプトから確認
C:\work\go\sqlite>sqlite3 test.db
SQLite version 3.10.2 2016-01-20 15:27:19
Enter ".help" for usage hints.
sqlite> select * from world;
1|日本|東京
2|アメリカ|ワシントンD.C.
3|ロシア|モスクワ
4|イギリス|ロンドン
5|オーストラリア|シドニー

データの表示

package main

import (
	"fmt"
	"database/sql"
	_ "github.com/mattn/go-sqlite3"
)

func main(){
	var id int
	var country string
	var capital string

	db, err := sql.Open("sqlite3", "./test.db")
	if err != nil { panic(err) }

	rows, err := db.Query( `SELECT * FROM world` )
	if err != nil { panic(err) }

	for rows.Next() {
		err = rows.Scan(&id, &country, &capital)
		if err != nil { panic(err) }
		fmt.Println(id, " ", country, " ", capital)
	}

	db.Close()
}

データの更新

package main

import (
	"fmt"
	"database/sql"
	_ "github.com/mattn/go-sqlite3"
)

func main(){
	
	var dbfile string = "./test.db"

	db, err := sql.Open("sqlite3", dbfile)
	if err != nil { panic(err) }

	stmt, err := db.Prepare( `UPDATE "world" SET capital=? WHERE country=?` )
	if err != nil { panic(err) }

	res, err := stmt.Exec("キャンベラ", "オーストラリア")
	if err != nil { panic(err) }

	affect, err := res.RowsAffected()
	if err != nil { panic(err) }

	fmt.Println(affect, "個のデータを更新しました。")
	stmt.Close()

	db.Close()
}