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