【问题标题】:Convert bytea with multiple octals to an integer将具有多个八进制的 bytea 转换为整数
【发布时间】:2017-02-11 22:50:16
【问题描述】:

我正在尝试从存储为 bytea 的 Postgres 数据库中获取值。
这些值是 VLAN ID(因此是 1-4096 之间的整数)。

但是,它存储在数据库中(例如):

\000\000\001\221 (equal to 401)

如果可能的话,我想让我的 SQL 查询将整数值返回给我的 python 代码。

经过一番搜索,我可以使用 get_byte 来获取这 4 个八进制之一(通过指定位置):

select get_byte(sub.datavlan_bytes,3) AS vlan -> this gives me the value of /221 (145)

但是,我无法获得全部价值。

有没有一种在选择查询中获取数据的好方法,或者这需要在我的脚本中进行吗?

【问题讨论】:

    标签: python sql postgresql


    【解决方案1】:

    通过强制转换的纯 SQL:

    select ('x' || encode(o, 'hex'))::bit(32)::int
    from (values ('\000\000\001\221'::bytea)) s (o)
    ;
     int4 
    ------
      401
    

    【讨论】:

    • 是的,不需要 plpgsql,只需转换即可。
    【解决方案2】:

    Postgres 9+ 为 bytea 值提供了 hex 格式。如果您可以将bytea_output 连接设置设置为hex(这是默认设置,所以它可能已经是...),您可以获得一个可以提供给Python 的int(..., 16) 函数的字符串。那将直接获得您的 401。

    编辑: Postgres 文档:https://www.postgresql.org/docs/9.0/static/datatype-binary.html

    【讨论】:

      猜你喜欢
      • 2016-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-24
      • 1970-01-01
      • 1970-01-01
      • 2011-10-31
      • 2017-02-19
      相关资源
      最近更新 更多