Middle — Middle+
What approaches exist for dynamically constructing SQL SELECT queries with the ability to change conditions and parameters?
sobes.tech AI
Answer from AI
For dynamically constructing a SELECT SQL query in Go, there are several approaches:
-
String concatenation — the simplest but unsafe method, prone to SQL injection.
-
Using parameterized queries with the
database/sqlpackage and passing arguments via?or$1. -
Query builders — libraries that allow programmatic query formation with conditions, sorting, etc.
Example using the Squirrel library:
import (
"github.com/Masterminds/squirrel"
"database/sql"
_ "github.com/lib/pq"
)
func buildQuery(age int, active bool) (string, []interface{}, error) {
qb := squirrel.Select("id", "name").From("users")
if age > 0 {
qb = qb.Where(squirrel.Gt{"age": age})
}
if active {
qb = qb.Where(squirrel.Eq{"active": true})
}
return qb.ToSql()
}
func main() {
db, _ := sql.Open("postgres", "connection_string")
query, args, _ := buildQuery(30, true)
rows, _ := db.Query(query, args...)
defer rows.Close()
// process results
}
This approach allows dynamic addition of conditions and parameters, avoiding errors and SQL injection.
You can also use ORM or custom query construction wrappers.