一尘不染

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

sql

我有一个Python脚本,可让我使用Python中的SQL查询GIS数据库

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)

该脚本可以正常工作,但是输出有点难以阅读:

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

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]
+++++++++++++++++++++++++++++++++++++++++++++

如果结果集可以更传统的表格格式输出,将很有帮助。像这样的东西会很棒(尽管我还没有嫁给这个确切的布局):

 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

我怎样才能做到这一点?我不确定如何格式化值,因为它们在列表中。我不太担心格式化COSTas货币;我可以在SQL中做到这一点。


阅读 232

收藏
2021-05-16

共1个答案

一尘不染

print((“{:<15}”len(row)).format(row))

将为您提供len(row)左对齐的列:

>>> row = [1, 3.4, "Pie", "pi", "a"]
>>> print(("{:<15}"*len(row)).format(*row))
1              3.4            Pie            pi             a

这只是"{:<15}"*len(row)为了获取"{:<15}{:<15}...{:<15}"然后格式化行中的值。

2021-05-16