dongming0505 2015-06-16 12:16
浏览 170
已采纳

Golang ORDER BY问题与MySql

I can't seem to dynamically ORDER BY with db.Select(). I've Googled without any 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'm not getting any errors, the query simply fails to order.

  • 写回答

1条回答 默认 最新

  • dongmi3203 2015-06-16 12:31
    关注

    Placeholders ('?') can only be used to insert dynamic, escaped values for filter parameters (e.g. in the WHERE part), where data values should appear, not for SQL keywords, identifiers etc. You cannot use it to dynamically specify the ORDER BY OR GROUP BY values.

    You can still do it though, for example you can use fmt.Sprintf() to assemble the dynamic query text like this:

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

    Things to keep in mind:

    Doing so you will have to manually defend vs SQL injection, e.g. if the value of the column name comes from the user, you cannot accept any value and just insert it directly into the query else the user will be able to do all kinds of bad things. Trivially you should only accept letters of the English alphabet + digits + underscore ('_').

    Without attempting to provide a complete, all-extensive checker or escaping function, you can use this simple regexp which only accepts English letters, digits and '_':

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

    Examples (try it on the Go Playground):

    fmt.Println(valid.MatchString("title"))         // true
    fmt.Println(valid.MatchString("another_col_2")) // true
    fmt.Println(valid.MatchString("it's a trap!"))  // false
    fmt.Println(valid.MatchString("(trap)"))        // false
    fmt.Println(valid.MatchString("also*trap"))     // false
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?