du0173 2016-03-22 16:31
浏览 30
已采纳

使用uuid字符串列表选择进入

I have a list of uuid strings that I want to use to filter a query. I can get the query to work if I loop over elements in my list like so:

for i, fileUID := range fileUIDs {
    db.Exec("DELETE FROM files WHERE uid = $1::uuid", fileUID)
}

But I'd like to get it working using the list:

db.Exec("DELETE FROM files WHERE uid IN $1::uuid[]", fileUIDs)

Is this possible? I can't seem to get it working.

I tried the solution in How to execute an IN lookup in SQL using Golang? but I get errors like pq: syntax error at or near "," when using plain ? or pq: syntax error at or near "::" when using ?:uuid. I used the following:

fileUIDArgs := make([]interface{}, len(fileUIDs))
for i, fileUID := range fileUIDs {
    fileUIDArgs[i] = interface{}(fileUID)
}
//also tried using "?::uuid"
myPsql := "DELETE FROM files WHERE uid IN (" + "?" + strings.Repeat(",?", len(uidStrings)-1) + ")"
db.Exec(myPsql, fileUIDArgs...)
  • 写回答

1条回答 默认 最新

  • duanmu2941 2016-03-22 20:23
    关注

    Using fmt. Make sure that your uuids doesn't contain any SQL-injection.

    ary := []string{
        "1442edc8-9e1f-4213-8622-5610cdd66790",
        "0506ca17-d254-40b3-9ef0-bca6d15ad49d",
        "e46f3708-6da5-4b82-9c92-f89394dffe5d",
        "fb8bf848-73a2-4253-9fa3-e9d5e16ef94a",
        "84691fa5-3391-4c02-9b16-82389331b7ac",
        "adba3c9d-b4ab-4e62-a650-414970645be7",
    }
    query := fmt.Sprintf(`DELETE FROM files WHERE uid IN ('%s'::uuid);`,
                 strings.Join(ary, "'::uuid,'"))
    db.Exec(query) // etc
    

    play.golang.org


    Rid out of potential SQL-injections:

    ary := []string{ /* list of uuids */ }
    query := `DELETE FROM files WHERE uid IN (`
    aryInterfaces := make([]interface{}, len(ary))
    for i, v := range ary {
        query += "$" + strconv.FormatInt(int64(i+1), 10)
        if i < len(ary)-1 {
            query += ","
        }
        aryInterfaces[i] = v
    }
    query += ")"
    db.Exec(query, aryInterface...)
    

    play.golang.org


    BONUS Postgresql uses $1, $2, $3 etc instead of ?, ?, ?. Here is a little helper function and here is its proof of concept.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么