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