Golang+Postgres WHERE子句与十六进制值

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

Golang+Postgres WHERE clause with a hex value

问题

你好!根据你提供的信息,你创建了一个包含BYTEA字段的简单SQL数据库,并尝试从Go语言中查询它。然而,查询似乎无法找到行。你想知道自己做错了什么。

根据你提供的代码,问题可能出在查询参数的格式上。在Go语言中,使用$1作为占位符表示查询参数,但是在你的代码中,你使用了\x123456作为参数。这可能导致查询无法正确匹配到结果。

你可以尝试将查询参数修改为'\x123456',即在参数前后添加单引号,以确保参数被正确解析。修改后的代码如下:

package main

import (
	"database/sql"
	_ "github.com/lib/pq"
)

func main(){
	var err error

	db, err := sql.Open("postgres", "dbname=testhex sslmode=disable")
	if err != nil {
		panic(err)
	}

	var result string
	err = db.QueryRow("select testhex from testhex where testhex = $1", `'\x123456'`).Scan(&result)
	if err != nil {
		panic(err)
	}
}

请尝试修改代码并重新运行查询,看看是否能够找到正确的行。如果问题仍然存在,请提供更多的信息,以便我能够更好地帮助你解决问题。

英文:

I created a simple sql database with a BYTEA field,

create table testhex (testhex bytea);
insert into testhex (testhex) values ('\x123456');

and then I tried to query it from Go.

package main

    import (
    	"database/sql"
    	_ "github.com/lib/pq"
    )
    
    func main(){
    	var err error
    
    	db, err := sql.Open("postgres", "dbname=testhex sslmode=disable")
    	if err != nil {
    		panic(err)
    	}
    
    	var result string
    	err = db.QueryRow("select testhex from testhex where testhex = $1", `\x123456`).Scan(&result)
    	if err != nil {
    		panic(err)
    	}
    }

It doesn't find the row. What am I doing wrong?

答案1

得分: 3

当你运行以下查询时:

insert into testhex (testhex) values ('\\x123456');

你将3字节序列[0x12 0x34 0x56]插入到表中。但是,对于你使用QueryRow执行的数据库查询,你正在搜索8个字符的字面字符串\x123456,所以在结果中找不到匹配项。

当你在QueryRow中使用位置参数时,数据库适配器的工作是将它们转换为数据库可以理解的形式(通过将它们作为绑定参数发送到数据库,或者通过适当的转义将它们替换到查询中)。因此,通过传递已经转义的值,你会遇到这种问题。

相反,尝试将[]byte{0x12, 0x34, 0x56}作为位置参数传递,这应该与数据库中的内容匹配。

英文:

When you ran the following query:

insert into testhex (testhex) values ('\x123456');

You inserted the 3 byte sequence [0x12 0x34 0x56] into the table. For the database query you're executing with QueryRow though, you're searching for the 8 character literal string \x123456 so you get no matches in the result.

When you use positional arguments with QueryRow, it is the database adapter's job to convert them to a form the database understands (either by sending them to the database as bound parameters, or by substituting them into the query with appropriate escaping). So by passing an already escaped value you will run into this sort of problem.

Instead, try passing []byte{0x12, 0x34, 0x56} as the positional argument, which should match what is in the database.

huangapple
  • 本文由 发表于 2014年12月12日 10:01:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/27435688.html
匿名

发表评论

匿名网友

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

确定