Psycopg2查询返回Decimal('value')

tau*_*ich 6 python postgresql psycopg2

我在Python中查询一个查询PostgreSQL数据库(通过psycopg2)。我的代码返回的值为Decimal('VALUE')。有什么办法可以在数据库中转换它吗?代码示例:

query = "SELECT id FROM table;"
cur.execute(query)
results = cur.fetchall()
# Results = Decimal('some value')   
Run Code Online (Sandbox Code Playgroud)

无论如何,是否可以将其转换为仅显示不带“ Decimal()”的值?也许我的架构设置错误?

小智 14

非常烦人的问题,我自己也遇到过。我在 SQL 中通过将列强制转换为浮点数解决了这个问题。在您的查询中:

query = "SELECT id::float as id FROM table;"
cur.execute(query)
results = cur.fetchall()
# Results = Decimal('some value')   

Run Code Online (Sandbox Code Playgroud)


Sin*_*ion 6

您所看到的是repr()一个decimal.Decimal()值的,它可以精确地表示十进制值,这是floats 不可用的功能。但是,如果您想看到一个很好的字符串表示形式(例如,保留到小数点后6位),则不会失去实用性,只需float使用str或来格式化它就可以了format。

In [7]: str(decimal.Decimal('0.1'))
Out[7]: '0.1'

In [13]: "{0:0.6f}".format(decimal.Decimal('0.1'))
Out[13]: '0.100000'
Run Code Online (Sandbox Code Playgroud)