54
loading...
This website collects cookies to deliver better user experience
package main
import (
"fmt"
"strings"
)
var filters = []struct {
Name string
Value interface{}
}{
{
Name: "name",
Value: "Homer",
},
{
Name: "city",
Value: "Springfield",
},
}
func main() {
query := "SELECT * FROM person"
var where []string
var args []interface{}
index := 0
// Make sure 'filters' are not provided by the client, or are checked against a list of allowed values, so that you don't give an opening for a SQL injection attack:
for _, filter := range filters {
index++
where = append(where, fmt.Sprintf("%s = $%d", filter.Name, index))
args = append(args, filter.Value)
}
if len(where) > 0 {
query = query + " WHERE " + strings.Join(where, " AND ")
}
fmt.Println(query)
// db.Query(query, args...)
_ = args
}
SELECT * FROM person WHERE name = $1 AND city = $2
package main
import (
"database/sql"
)
type filter struct {
Name sql.NullString
City sql.NullString
DOBBefore sql.NullTime
DOBAfter sql.NullTime
}
func main() {
var f filter
f.Name = sql.NullString{String: "Homer", Valid: true}
f.City = sql.NullString{String: "Springfield", Valid: true}
query := `
SELECT * FROM person
WHERE
($1 IS NULL OR name = $1) AND
($2 IS NULL OR city = $2) AND
($3 IS NULL OR dob < $3) AND
($4 IS NULL OR dob > $4)
`
rows, err := db.Query(query, f.Name, f.City, f.DOBBefore, f.DOBAfter)
[...]
}