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