パラメータ化されたステートメント
次のコード例は、パラメータをバインドしてパラメータ化されたステートメントを作成する方法を示します。
シングルユース ステートメント
Query とExec 関数は両方とも、クエリパラメータを値にバインドするための追加パラメータを受け入れます。
rows, _ := db.Query("SELECT SearchKeyword, SearchPeriod FROM SearchRanking WHERE SearchPeriod = ?", "weekly")
defer rows.Close()
for rows.Next() {
var (
SearchKeyword string
SearchPeriod string
)
rows.Scan(&SearchKeyword, &SearchPeriod)
fmt.Printf("SearchKeyword = %s, SearchPeriod = %s\n", SearchKeyword, SearchPeriod)
}
リユーザブル ステートメント
Prepare 関数は、プリペアドStmt オブジェクトを作成します。これは、複数のQuery およびExec 呼び出しで再利用できます。
stmt, _ := db.Prepare("SELECT SearchKeyword, SearchPeriod FROM SearchRanking WHERE SearchPeriod = ?")
defer stmt.Close()
rows, _ := stmt.Query("weekly 1")
defer rows.Close()
for rows.Next() {
var (
SearchKeyword string
SearchPeriod string
)
rows1.Scan(&SearchKeyword, &SearchPeriod)
fmt.Printf("SearchKeyword = %s, SearchPeriod = %s\n", SearchKeyword, SearchPeriod)
}
rows, _ = stmt.Query("weekly 2")
defer rows.Close()
for rows.Next() {
var (
SearchKeyword string
SearchPeriod string
)
rows2.Scan(&SearchKeyword, &SearchPeriod)
fmt.Printf("SearchKeyword = %s, SearchPeriod = %s\n", SearchKeyword, SearchPeriod)
}