【问题标题】:Select/Fetch signed integer in PostgreSQL/Python在 PostgreSQL/Python 中选择/获取有符号整数
【发布时间】:2015-07-29 20:25:10
【问题描述】:

我想从 measurements 表的 measurement_id 列中选择和获取整数,否则,我会以某种方式将单项大小的元组转换为有符号整数通过 Python 的一些后处理。 我在 MySQL 中知道这个 Selecting/casting output as integer in SQL,其中我的 PostgreSQL 9.4 伪代码

CREATE TABLE measurements (
        measurement_id SERIAL PRIMARY KEY NOT NULL,
        measurement_size_in_bytes INTEGER NOT NULL,
        time TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP
);  

-- sample data
INSERT INTO measurements (measurement_size_in_bytes) VALUES (77777), (5065), (888);

SELECT CAST(measurement_id AS SIGNED) FROM measurements ORDER BY time desc limit 1;

投射不起作用的地方,即使是measurement_id::int。 可能,format 是这里的正确工具。 执行print "measurement_id ", _measurement_id; 给出元组((21,)),而它应该只给出21

在 Python 中启动和运行

sudo -u postgres psql detector -f 12.7.2015_creates.sql;
DROP TABLE
CREATE TABLE
$ sudo -u postgres psql detector -c "INSERT INTO measurements (measurement_size_in_bytes) VALUES (77777), (5065), (888);"
INSERT 0 3
$ sudo -u postgres psql detector -c "INSERT INTO measurements (measurement_size_in_bytes) VALUES (77777), (5065), (888);"
INSERT 0 3
$ sudo -u postgres psql detector -c "SELECT measurement_id FROM measurements ORDER BY time desc limit 1";
 measurement_id 
----------------
              7
(1 row)

但是在我需要使用数据的 Python 中做同样的事情

import sys
import os
import struct
import psycopg2
conn_string = "dbname=detector user=postgres password=1234 host=localhost port=5432"
print "Connecting to database\n    ->%s" % (conn_string)     
conn = psycopg2.connect(conn_string)
cursor = connection.cursor()
cursor.execute(
    'SELECT measurement_id FROM measurements ORDER BY time desc limit 1;'
);
_measurement_id = cursor.fetchone();
print "measurement_id ", _measurement_id, " javist!";

返回

Connecting to database
    ->dbname=detector user=postgres password=1234 host=localhost port=5432
measurement_id  (11,)  javist!

我想从打印中获得measurement_id 11 javist!

如何从 PostgreSQL/Python 中的元组中选择/获取有符号整数?

操作系统:Debian 8.5
硬件:联想

【问题讨论】:

  • 你的意思是measurement_id不是一个int?为什么不呢?
  • 编辑您的问题并为measurements 添加create table 语句,理想情况下是一些重现此行为的示例数据(如insert 语句)。 cast(.. as signed) 对 Postgres 无效,因为 signed 在 Postgres 中不是有效的数据类型
  • 如果您向我们展示measurement 的实际含义,将会有所帮助。
  • 插入和选择都不会执行。插入尝试将数据放入不存在的列中,并且选择使用 postgresql 中不存在的类型 SIGNED。我也没有看到演员阵容的原因。 measure_id 被声明为一个序列,它是一个具有序列默认值的整数,并且整数是有符号的。
  • 好的,你能不能修复 SELECT 让它执行并显示问题?

标签: python postgresql casting tuples psycopg2


【解决方案1】:

fetchone 返回一个元组。只需获取它的第一个元素:

_measurement_id = cursor.fetchone()[0];

【讨论】:

    猜你喜欢
    • 2010-11-25
    • 1970-01-01
    • 2012-04-01
    • 2014-02-20
    • 2014-01-13
    • 1970-01-01
    • 1970-01-01
    • 2015-10-28
    • 2023-03-31
    相关资源
    最近更新 更多