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 AccountId, AccountNumber FROM Accounts WHERE ModifiedBy = ?", "System") defer rows.Close() for rows.Next() { var ( AccountId string AccountNumber string ) rows.Scan(&AccountId, &AccountNumber) fmt.Printf("AccountId = %s, AccountNumber = %s\n", AccountId, AccountNumber) }
Reusable Statements
The Prepare function creates prepared Stmt objects, which can be re-used across multiple Query and Exec calls.
stmt, _ := db.Prepare("SELECT AccountId, AccountNumber FROM Accounts WHERE ModifiedBy = ?") defer stmt.Close() rows, _ := stmt.Query("System 1") defer rows.Close() for rows.Next() { var ( AccountId string AccountNumber string ) rows1.Scan(&AccountId, &AccountNumber) fmt.Printf("AccountId = %s, AccountNumber = %s\n", AccountId, AccountNumber) } rows, _ = stmt.Query("System 2") defer rows.Close() for rows.Next() { var ( AccountId string AccountNumber string ) rows2.Scan(&AccountId, &AccountNumber) fmt.Printf("AccountId = %s, AccountNumber = %s\n", AccountId, AccountNumber) }