【发布时间】:2016-08-13 14:37:22
【问题描述】:
我正在尝试输出我的数据库表数据,除了长表行之外,它还可以工作。列需要与最长的数据库行一样大。当输出长行时(不使用第三方库,例如Print results in MySQL format with Python),我无法执行计算以按比例正确输出表格,而不是造成巨大的混乱。如果您需要更多信息,请告诉我。
数据库连接:
connection = sqlite3.connect("test_.db")
c = connection.cursor()
c.execute("SELECT * FROM MyTable")
results = c.fetchall()
formatResults(results)
表格格式:
def formatResults(x):
try:
widths = []
columns = []
tavnit = '|'
separator = '+'
for cd in c.description:
widths.append(max(cd[2], len(cd[0])))
columns.append(cd[0])
for w in widths:
tavnit += " %-"+"%ss |" % (w,)
separator += '-'*w + '--+'
print(separator)
print(tavnit % tuple(columns))
print(separator)
for row in x:
print(tavnit % row)
print(separator)
print ""
except:
showMainMenu()
pass
输出问题示例:
+------+------+---------+
| Date | Name | LinkOrFile |
+------+------+---------+
| 03-17-2016 | hi.com | Locky |
| 03-18-2016 | thisisitsqq.com | None |
| 03-19-2016 | http://ohiyoungbuyff.com\69.exe?1 | None |
| 03-20-2016 | http://thisisitsqq..com\69.exe?1 | None |
| 03-21-2016 | %Temp%\zgHRNzy\69.exe | None |
| 03-22-2016 | | None |
| 03-23-2016 | E52219D0DA33FDD856B2433D79D71AD6 | Downloader |
| 03-24-2016 | microsoft.com | None |
| 03-25-2016 | 89.248.166.132 | None |
| 03-26-2016 | http://89.248.166.131/55KB5js9dwPtx4= | None |
【问题讨论】:
-
您面临的具体问题是什么?
-
你打印了可变宽度的输出吗?它是否包含每列最长值的长度?
-
我不知道该怎么做。
-
在
formatResults第一次循环后,添加行print widths -
好的,我明白了:[4] [4, 4] [4, 4, 7]
标签: python mysql python-2.7 sqlite python-3.x