Golang Cafe #4 補足 データベースアクセス(MySQL編)

前回のエントリではGo言語でPostgreSQLに対する操作を行いましたが、MySQLでも試してみました。
やはりそのままのソースコードでは動作しなかったので変更、追加した部分だけをまとめておきます。
今回使用したMySQL用のドライバののドキュメントはこちらになります。


https://github.com/go-sql-driver/mysql/のドライバをインストールします。

$ go get github.com/go-sql-driver/mysql

MySQL用のドライバはhttps://github.com/ziutek/mymysqlもあるようですが、Go言語のdatabase/sqlパッケージのinterfaceを実装しているわけではなさそう今回は試しませんでした。


接続文字列を変更します。

root:mysql@tcp(localhost:3306)/godbtest
// ユーザ名:パスワード@プロトコル(ホスト:ポート)/データベース名?追加のパラメータ=値


クエリ文字列のplace folder を ? に変更

query := "insert into table1 (display_name, sex, birthday, age, married, rate, salary) "
query += "values (?, ?, ?, ?, ?, ?, ?)"


更新系ではQueryRowを使わずExecを使用します。
PostgreSQLでは動作しなかったLastInsertIdメソッドが正常に動作します。

var r = createRecord()
result, err := db.Exec(query, r.displayName, r.sex, r.birthday, r.age, r.married, r.rate, r.salary)

if c, err := result.LastInsertId(); err != nil {
    t.Errorf("LastInsertIdを取得できません。: %v", err)
} else {
    t.Logf("LastInsertId: %v", c)
}

if c, err := result.RowsAffected(); err != nil {
    t.Errorf("RowsAffectedを取得できません。: %v", err)
} else {
    t.Logf("RowsAffected: %v", c)
}
--- PASS: Test1件追加_Execを使用 (0.00 seconds)
        03.insert_test.go:36: LastInsertId: 11
        03.insert_test.go:42: RowsAffected: 1


nilのカラムを扱うための型をpq.NullTimeをmysql.NullTimeに変更します。
MySQLの場合でもドライバ側で定義されるようです。

type Record struct {
    id int
    displayName sql.NullString
    sex string
    birthday mysql.NullTime
    age sql.NullInt64
    married sql.NullBool
    rate sql.NullFloat64
    salary sql.NullInt64
}


前回のエントリでも書きましたが、最初にMySQLで試したほうがスムーズでよかったかもしれません。

https://github.com/taknb2nch/godbtest/tree/master/mysqlにサンプルコード一式を置いておきます。(今後リポジトリは変更になるかもしれません)