lenpython执行结果_从Python执行SQL:格式化结果集

I have a python script that lets me query a GIS database using SQL in Python:

import sys

import arcpy

try:

arcpy.env.workspace = sys.path[0]

egdb_conn = arcpy.ArcSDESQLExecute(r"Database Connections\Connection1.sde")

--> sql_statement = """SELECT * FROM USER1.A_TEST_TABLE"""

sql_statement_list = sql_statement.split(";")

print("+++++++++++++++++++++++++++++++++++++++++++++\n")

# For each SQL statement passed in, execute it.

for sql in sql_statement_list:

print(sql)

try:

egdb_return = egdb_conn.execute(sql)

except Exception as err:

print(err)

egdb_return = False

if isinstance(egdb_return, list):

for row in egdb_return:

print(row)

print("+++++++++++++++++++++++++++++++++++++++++++++\n")

else:

if egdb_return == True:

print("SQL statement: {0} ran successfully.".format(sql))

else:

print("SQL statement: {0} FAILED.".format(sql))

print("+++++++++++++++++++++++++++++++++++++++++++++\n")

except Exception as err:

print(err)

The script works just fine, but the output is a little hard to read:

+++++++++++++++++++++++++++++++++++++++++++++

SELECT * FROM INFRASTR.A_TEST_TABLE

[1, u'1', u'APPLE', 0.1]

[2, u'2', u'PEAR', 0.2]

[3, u'3', u'BANANA', 0.3]

[4, u'4', u'MANGO', 0.4]

[5, u'5', u'ORANGE', 0.5]

[6, u'6', u'BLUEBERRY', 0.6]

[7, u'7', u'STRAWBERRY', 0.7000000000000001]

[8, u'8', u'RASPBERRY', 0.8]

[9, u'9', u'KIWI', 0.9]

[10, u'10', u'PINEAPPLE', 1.0]

+++++++++++++++++++++++++++++++++++++++++++++

It would be helpful if the result set could be output in a more traditional table format. Something like this would be great (although I'm not married to this exact layout):

OBJECTID ID TYPE COST

1 1 APPLE 0.01

2 2 PEAR 0.02

3 3 BANANA 0.03

4 4 MANGO 0.04

5 5 ORANGE 0.05

6 6 BLUEBERRY 0.06

7 7 STRAWBERRY 0.07

8 8 RASPBERRY 0.08

9 9 KIWI 0.09

10 10 PINEAPPLE 1.00

How can I do this? I'm not sure how to format the values, since they're in a list. I'm not too worried about formatting the COST as currency; I can do that in SQL.

解决方案print(("{:<15}"*len(row)).format(*row))

will give you len(row) left aligned columns:

>>> row = [1, 3.4, "Pie", "pi", "a"]

>>> print(("{:<15}"*len(row)).format(*row))

1 3.4 Pie pi a

which is just doing "{:<15}"*len(row) to get "{:<15}{:<15}...{:<15}" then formatting in the values from row.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值