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

Execute SQL from Python: Format the result set

本问题已经有最佳答案,请猛点这里访问。

我有一个python脚本,允许我在python中使用SQL查询一个gis数据库:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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("+++++++++++++++++++++++++++++++++++++++++++++
"
)
    # 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("+++++++++++++++++++++++++++++++++++++++++++++
"
)
        else:
            if egdb_return == True:
                print("SQL statement: {0} ran successfully.".format(sql))
            else:
                print("SQL statement: {0} FAILED.".format(sql))
            print("+++++++++++++++++++++++++++++++++++++++++++++
"
)
except Exception as err:
    print(err)

脚本工作正常,但输出有点难读取:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
+++++++++++++++++++++++++++++++++++++++++++++

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

如果结果集可以以更传统的表格式输出,这将很有帮助。像这样的事情会很好(尽管我还没有和这个确切的布局结婚):

1
2
3
4
5
6
7
8
9
10
11
 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

我该怎么做?我不知道如何格式化这些值,因为它们在一个列表中。我不太担心将COST格式化为货币;我可以在SQL中这样做。


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

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

1
2
3
>>> 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}",然后格式化行中的值。


您可以将输出传递到字典和熊猫数据帧。也许有一种更有效的方法,但像这样的方法是可行的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import pandas

s = []
for row in egdb_return:
    r = []
    r.append(row)
    d = {}
    d["ObjectId"] = r.[1]
    d["ID"] = r[2]
    d["Type"] = r[3]
    d["Cost"] = r[4]
    s.append(d)

Table = pandas.dataframe(s)
print(Table)