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