Last active
November 22, 2018 02:19
-
-
Save shumon84/285745829260ddfaba34e472ab478ba5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"database/sql" | |
_ "github.com/go-sql-driver/mysql" | |
) | |
func main() { | |
db, _ := sql.Open("mysql", "user:password@tcp(host:port)/dbname") | |
tx, _ := db.Begin() // トランザクション開始 | |
defer func() { | |
// panicが起きたらロールバック | |
if recover() != nil { | |
tx.Rollback() | |
} | |
}() | |
// 普通のクエリはsql.DBと同じように使える | |
tx.Exec("INSERT INTO hoge (id) VALUES (?)", "0000") | |
tx.Query("SELECT * FROM hoge WHERE id = ?", "0000") | |
tx.QueryRow("SELECT * FROM hoge") | |
// prepared statementを使うときは注意する | |
// sql.DBでprepareしたやつはトランザクションに含まれない | |
stmt, _ := db.Prepare("INSERT INTO hoge (id) VALUES (?)") | |
stmt.Exec("0000") // トランザクションに含まれない | |
// Stmt()で変換してから使うとトランザクションに含まれる | |
stmt = tx.Stmt(stmt) | |
stmt.Exec("0000") // トランザクションに含まれる | |
// sql.Txでprepareしたやつはトランザクションに含まれる | |
stmt, _ := tx.Prepare("INSERT INTO hoge (id) VALUES (?)") | |
stmt.Exec("0000") // トランザクションに含まれる | |
// 何かの処理で問題が起こったとき | |
if err != nil { | |
tx.Rollback() // ロールバック | |
} else { | |
tx.Commit() // コミット | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment