Sos*_*mqk -1 python python-2.x
我有一个连接到数据库的小应用程序.我可以使用raw_input插入数据,然后我选择查询以返回一些结果作为报告.
这是代码片段:
if user_input == 'Y':
cursor.execute(SQLCommand, Values)
cursor.execute(SQLCommand1)
result = cursor.fetchall()
print 'The total costs until now are '
print result
Run Code Online (Sandbox Code Playgroud)
这是输出:
The total costs until now are
[(2061.1, )]
Run Code Online (Sandbox Code Playgroud)
我只需要看到数字,没有任何特殊字符.我应该使用pprint吗?
谢谢
该[]输出指的result是一个列表.在列表中,()表示列表的单个元素是元组.如果您不熟悉列表和元组,那么您肯定需要在官方Python教程中阅读它们.这些是Python编程的基础.
有两种方法可以获得所需的结果.
按行和列位置索引:
print result[0][0]
Run Code Online (Sandbox Code Playgroud)按行位置和列名称索引:
print result[0]['total']
Run Code Online (Sandbox Code Playgroud)注意
如果您知道只从查询中获得一行,则还可以使用fetchone()而不是fetchall():
result = cursor.fetchone()
print result['total']
Run Code Online (Sandbox Code Playgroud)