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 OptyId, Name FROM Opportunities WHERE CreatedBy = ?", "Jack") defer rows.Close() for rows.Next() { var ( OptyId string Name string ) rows.Scan(&OptyId, &Name) fmt.Printf("OptyId = %s, Name = %s\n", OptyId, 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 OptyId, Name FROM Opportunities WHERE CreatedBy = ?") defer stmt.Close() rows, _ := stmt.Query("Jack 1") defer rows.Close() for rows.Next() { var ( OptyId string Name string ) rows1.Scan(&OptyId, &Name) fmt.Printf("OptyId = %s, Name = %s\n", OptyId, Name) } rows, _ = stmt.Query("Jack 2") defer rows.Close() for rows.Next() { var ( OptyId string Name string ) rows2.Scan(&OptyId, &Name) fmt.Printf("OptyId = %s, Name = %s\n", OptyId, Name) }