Question GOLAN ORDER BY with MySql

I cannot dynamically program ORDER BY with db.Select (). I googled with no luck ...

WORKS

rows, err := db.Query("SELECT * FROM Apps ORDER BY title DESC")

DOES NOT WORK

rows, err := db.Query("SELECT * FROM Apps ORDER BY ? DESC", "title")

I do not receive any errors, the request simply cannot be ordered.

+4
source share
1 answer

Placeholders ( '?') can only be used to insert dynamic shielded values ​​for filter parameters (for example, in parts WHERE) where data values ​​should be displayed, and not for SQL keywords, identifiers, etc. You cannot use it to dynamically specify ORDER BYOR values GROUP BY.

You can still do this, for example, you can use fmt.Sprintf()to build dynamic query text as follows:

ordCol := "title"

qtext := fmt.Sprintf("SELECT * FROM Apps ORDER BY %s DESC", ordCol)
rows, err := db.Query(qtext)

:

, SQL-, . , - , . + + ('_').

, , , , '_':

valid := regexp.MustCompile("^[A-Za-z0-9_]+$")
if !valid.MatchString(ordCol) {
    // invalid column name, do not proceed in order to prevent SQL injection
}

( Go Playground):

fmt.Println(valid.MatchString("title"))         // true
fmt.Println(valid.MatchString("another_col_2")) // true
fmt.Println(valid.MatchString("it a trap!"))  // false
fmt.Println(valid.MatchString("(trap)"))        // false
fmt.Println(valid.MatchString("also*trap"))     // false
+4

All Articles