Pyodbc返回(Decimal('100.00'),)

2024-10-01 13:35:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用pyodbc从一个表中读取一个数值,但是它不是只给出'100',而是给我“(Decimal('100.00'),)。在

有没有办法只得到号码?在

我在跑步:

cursor.execute("SELECT CurrentBalance as Numeric FROM [AccountsQA].[dbo].[AccountBalance] where AccountId = '2000013' and Currency = 'ZAR'")

如果这个问题已经得到了回答,我很抱歉,但是我还没有找到解决的办法。在


Tags: fromexecuteasselect跑步cursor号码数值
3条回答

假设表将该列定义为DECIMAL类型,因此pyodbc返回一个Decimal对象来忠实地表示该值。在

假设值在小数点后可能有数字,您可以通过调用float()来“只获取数字”,但是如果列表示货币(正如名称“CurrentBalance”所暗示的那样),则您不希望这样做。使用float值来表示金钱是一个不好的主意。在

相反,您可能应该继续使用十进制值。在

我知道这个问题已经有三年的历史了,但是如果它能帮助其他人搜索,我的建议是导入熊猫并用它来解析它。这种方法在很多场合对我有帮助。在

import pyodbc
import pandas as pd
conn = pyodbc.connect('Driver={SQL Server};'
                      'Server=YourServer;'
                      'Database=YourDatabase;') 
##this is for trusted connection.  
###You may also need to add  Username and password for your code

data = pd.read_sql_query(("SELECT CurrentBalance as Numeric FROM [AccountsQA].[dbo].[AccountBalance] where AccountId = '2000013' and Currency = 'ZAR'"), conn)

print(data.CurrentBalance[0])

这将为您提供CurrentBalance列中第一个响应的值。在

我通过以下操作设法得到了号码:

cursor.execute("SELECT CurrentBalance as Numeric FROM [AccountsQA].[dbo].[AccountBalance] where AccountId = '2000013' and Currency = 'ZAR'")
result = cursor.fetchall()
amount = result[0][0]

“result[0]”返回“(Decimal('100.00'),)”,但当我使用“result[0][0]时,它只返回“100.00”

相关问题 更多 >