dongrunying7537 2014-12-12 02:01
浏览 61
已采纳

具有十六进制值的Golang + Postgres WHERE子句

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条回答 默认 最新

  • doutenggu4070 2014-12-13 02:13
    关注

    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.

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

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?