我有一个我想用来过滤查询的uuid字符串列表。如果我循环遍历列表中的元素,我可以使查询起作用:
for i, fileUID := range fileUIDs {
db.Exec("DELETE FROM files WHERE uid = $1::uuid", fileUID)
}
但我想使用列表让它工作:
db.Exec("DELETE FROM files WHERE uid IN $1::uuid[]", fileUIDs)
这可能吗?我似乎无法让它发挥作用。
我在How to execute an IN lookup in SQL using Golang?中尝试了解决方案但在使用pq: syntax error at or near ","
时使用普通?
或pq: syntax error at or near "::"
时出现?:uuid
错误。我使用了以下内容:
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...)
答案 0 :(得分:2)
使用fmt。确保您的uuids不包含任何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
摆脱潜在的SQL注入:
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...)
<强>奖金强>
Postgresql使用$1, $2, $3
等而不是?, ?, ?
。这是一个小helper function和here是它的概念证明。
答案 1 :(得分:0)
这是一个老问题,但为了将被引导到这里的人,如果您使用的是 postgres db,您可以使用这种更简单的方法:
DELETE FROM files WHERE uid=ANY($1);
$1
是一个 uuid 数组。所以你的查询变成:
toBeDeleted:= []uuid.UUID{....}
_, err = tx.Exec("UDELETE FROM files WHERE uid=ANY($1);",toBeDeleted)
//or
_, err = tx.Exec("UDELETE FROM files WHERE uid=ANY($1);",pq.Array(toBeDeleted))
两者都适合你。