Parameterized Statements
The following code example shows how to bind parameters to create parameterized statements.
Single-Use Statements
The Query and Exec functions both accept additional parameters for binding query parameters to values.
rows, _ := db.Query("SELECT SalesPerson, Name FROM Contact WHERE Country = ?", "U.S.A.") defer rows.Close() for rows.Next() { var ( SalesPerson string Name string ) rows.Scan(&SalesPerson, &Name) fmt.Printf("SalesPerson = %s, Name = %s\n", SalesPerson, Name) }
Reusable Statements
The Prepare function creates prepared Stmt objects, which can be re-used across multiple Query and Exec calls.
stmt, _ := db.Prepare("SELECT SalesPerson, Name FROM Contact WHERE Country = ?") defer stmt.Close() rows, _ := stmt.Query("U.S.A. 1") defer rows.Close() for rows.Next() { var ( SalesPerson string Name string ) rows1.Scan(&SalesPerson, &Name) fmt.Printf("SalesPerson = %s, Name = %s\n", SalesPerson, Name) } rows, _ = stmt.Query("U.S.A. 2") defer rows.Close() for rows.Next() { var ( SalesPerson string Name string ) rows2.Scan(&SalesPerson, &Name) fmt.Printf("SalesPerson = %s, Name = %s\n", SalesPerson, Name) }