命名查询无法解析映射。

huangapple go评论156阅读模式
英文:

Named query failing to parse map

问题

我有这段代码:

query := `
	SELECT
		co_username as username,
		co_password as password
	FROM
		servers.co
	WHERE
		co_url = concat('https://', :co_url)
`

args := map[string]interface{}{
	"co_url": in.Url,
}

rows, err := collectorsConfig.Db.NamedQueryContext(ctx, query, args)
if err != nil {
	msg := "Error getting co credentials for co '%s': %v"
	log.Error.Printf(msg, in.Url, err)
	return
}

运行这段代码时,我得到了以下错误:

Error getting co credentials for co 'some.random.fqdn': could not find name in map[string]interface {}{"co_url":"some.random.fqdn"}

但是,如果我重新编写代码如下:

in.Url = "https://" + in.Url

query := `
	SELECT
		co_username as username,
		co_password as password
	FROM
		servers.co
	WHERE
		co_url = :co_url
`

一切正常。为什么使用Concat函数时,命名输入不起作用呢?

英文:

I have this code segement

query := `
		SELECT
			co_username as username,
			co_password as password
		FROM
			servers.co
		WHERE
			co_url = concat('https://', :co_url)
	`

	args := map[string]interface{}{
		"co_url": in.Url,
	}

	rows, err := collectorsConfig.Db.NamedQueryContext(ctx, query, args)
	if err != nil {
		msg := "Error getting co credentials for co '%s': %v"
		log.Error.Printf(msg, in.Url, err)
		return
	}

When runnig this snippet, I get an error like this:

> Error getting co credentials for co 'some.random.fqdn': could not find
> name in map[string]interface {}{"co_url":"some.random.fqdn"}

But if I rework the snippet to be

in.Url = "https://" + in.Url

query := `
    		SELECT
    			co_username as username,
    			co_password as password
    		FROM
    			servers.co
    		WHERE
    			co_url = :co_url
    	`

Everything works. Is there a reason the named input is not working with the Concat function?

答案1

得分: 0

这将取决于你使用的sql库,但是在许多库中使用NamedQuery时,你必须转义任何其他冒号,你可以在其文档中找到如何进行转义的方法。例如,sqlx要求你用两个冒号来转义一个冒号,如下所示:

co_url = concat('https:://', :co_url)
英文:

This would depend on what sql library you are using, but when using NamedQuery in many libraries, you must escape any other colons, which you will find how to do in its documentation. For example, sqlx requires you to escape a colon with two e.g.

co_url = concat('https:://', :co_url)

huangapple
  • 本文由 发表于 2017年9月1日 19:21:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/45999194.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定