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