dow56114 2019-07-13 16:47
浏览 47
已采纳

在'Name =?'附近使用的正确语法

i'm trying to filter my registers with a "Name" parameter.

I make this handler function:

func GetFuncionaries(w http.ResponseWriter, r *http.Request) {
    var f model.Funcionary
    var t util.App
    var d db.DB
    err := d.Connection()
    db := d.DB
    defer db.Close()

    Id, _ := strconv.Atoi(r.FormValue("Id"))
    Name:= r.FormValue("Name")

    f.Id = int64(Id)
    f.Name = Name

    funcionaries, err := f.GetFuncionaries(db)
    if err != nil {
            log.Printf("[handler/GetFuncionaries-  Error: %s", err.Error())
            t.ResponseWithError(w, http.StatusInternalServerError, err.Error(), "")
        }
        return
    }
    t.ResponseWithJSON(w, http.StatusOK, funcionaries, 0, 0)
}

And the function model:

func (f *Funcionary) GetFuncionaries(db *sql.DB) ([]Funcionary, error) {
    var values []interface{}
    var where []string

    if f.Name != "" {
        where = append(where, "Name= ?")
        values = append(values, f.Name)
    }


    rows, err := db.Query(`SELECT Id, Data, Role, Name
                    FROM funcionaries
                    WHERE 1=1 `+strings.Join(where, " AND "), values...)
    if err != nil {
        return nil, err
    }

    funcionaries:= []Funcionary{}
    defer rows.Close()
    for rows.Next() {
        var funcionary Funcionary
        if err = rows.Scan(&funcionario.Id, &funcionario.Name, &Others...); err != nil {
            return nil, err
        }
        funcionaries = append(funcionaries, funcionary)
    }
    return funcionaries, nil
}

But when i make a call in postman like:

http://localhost:8000/api/funcionaries?Name=a

I receive the error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Name= ?' at line 3",

I'm forgetting something?

  • 写回答

1条回答 默认 最新

  • duanhan8757 2019-07-13 17:23
    关注

    It looks to me like the SQL string produced by your code will be

    SELECT Id, Data, Role, Name FROM funcionaries WHERE 1=1 Name= ?
    

    Whereas what you want is:

    SELECT Id, Data, Role, Name FROM funcionaries WHERE 1=1 AND Name= ?
    

    To do this you could modify your code like so:

    q := `SELECT Id, Data, Role, Name
              FROM funcionaries
              WHERE True`
    if len(where) != 0 {
        q = q + " AND " + strings.Join(where, " AND ")
    }
    rows, err := db.Query(q, values...)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 定制ai直播实时换脸软件
  • ¥100 栈回溯相关,模块加载后KiExceptionDispatch无法正常回溯了
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含
  • ¥15 麒麟V10桌面版SP1如何配置bonding
  • ¥15 Marscode IDE 如何预览新建的 HTML 文件
  • ¥15 K8S部署二进制集群过程中calico一直报错
  • ¥15 java python或者任何一种编程语言复刻一个网页
  • ¥20 如何通过代码传输视频到亚马逊平台