[英]Go Select In using a list of uuid strings
I have a list of uuid strings that I want to use to filter a query.我有一个 uuid 字符串列表,我想用它来过滤查询。 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?我尝试了如何使用 Golang 在 SQL 中执行 IN 查找中的解决方案? but I get errors like
pq: syntax error at or near ","
when using plain ?
但是我在使用普通时遇到类似
pq: syntax error at or near ","
?
or pq: syntax error at or near "::"
when using ?:uuid
.或
pq: syntax error at or near "::"
使用?:uuid
时pq: syntax error at or near "::"
。 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...)
Using fmt.使用 fmt。 Make sure that your uuids doesn't contain any SQL-injection .
确保您的 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
play.golang.org play.golang.org
Rid out of potential SQL-injections:摆脱潜在的 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...)
play.golang.org play.golang.org
BONUS Postgresql uses $1, $2, $3
etc instead of ?, ?, ?
奖励Postgresql 使用
$1, $2, $3
等代替?, ?, ?
. . Here is a little helper function and here is its proof of concept.
这是一个小辅助函数,这是它的概念证明。
This is an old question but for the sake of people who will be directed here, if you are using postgres db you can use this easier way:这是一个老问题,但为了将被引导到这里的人,如果您使用的是 postgres db,您可以使用这种更简单的方法:
DELETE FROM files WHERE uid=ANY($1);
$1
is an array of uuids. $1
是一组 uuid。 so your query becomes:所以你的查询变成:
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))
either should work for you.要么应该为你工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.