使用Python以MySQL格式打印结果

时间:2012-06-02 19:57:57

标签: python mysql

从MySQL查询中打印结果的最简单方法是什么,就像MySQL使用Python在控制台中打印它们一样?例如,我想得到类似的东西:

+---------------------+-----------+---------+
| font                | documents | domains |
+---------------------+-----------+---------+
| arial               |     99854 |    5741 |
| georgia             |     52388 |    1955 |
| verdana             |     43219 |    2388 |
| helvetica neue      |     22179 |    1019 |
| helvetica           |     16753 |    1036 |
| lucida grande       |     15431 |     641 |
| tahoma              |     10038 |     594 |
| trebuchet ms        |      8868 |     417 |
| palatino            |      5794 |     177 |
| lucida sans unicode |      3525 |     116 |
| sans-serif          |      2947 |     216 |
| times new roman     |      2554 |     161 |
| proxima-nova        |      2076 |      36 |
| droid sans          |      1773 |      78 |
| calibri             |      1735 |      64 |
| open sans           |      1479 |      60 |
| segoe ui            |      1273 |      57 |
+---------------------+-----------+---------+
17 rows in set (19.43 sec)

注意:我不知道每列的最大宽度是先验的,但我希望能够在没有超过表格两次的情况下完成。我应该为每列添加查询长度()吗? MySQL如何做到这一点,以免严重影响内存或处理时间?

修改

我认为这与问题无关,但这是我发送的查询:

SELECT font.font as font,count(textfont.textid) as documents, count(DISTINCT td.domain) as domains
FROM textfont 
RIGHT JOIN font
ON textfont.fontid = font.fontid
RIGHT JOIN (
        SELECT text.text as text,url.domain as domain, text.textid as textid 
        FROM text 
        RIGHT JOIN url 
        ON text.texturl = url.urlid) as td 
ON textfont.textid = td.textid
WHERE textfont.fontpriority <= 0 
AND textfont.textlen > 100
GROUP BY font.font 
HAVING documents >= 1000 AND domains >= 10
ORDER BY 2 DESC;

这是我使用的python代码:

import MySQLdb as mdb

print "%s\t\t\t%s\t\t%s" % ("font","documents","domains")
res = cur.execute(query , (font_priority,text_len,min_texts,min_domains))
for res in cur.fetchall():
    print "%s\t\t\t%d\t\t%d" % (res[0],res[1],res[2])

但由于宽度不同,此代码会产生混乱的输出。

5 个答案:

答案 0 :(得分:18)

不需要外部库。使用列名打印出数据。如果您不需要列名,则可以删除所有带有'columns'变量的行。

sql = "SELECT * FROM someTable"
cursor.execute(sql)
conn.commit()
results = cursor.fetchall()

widths = []
columns = []
tavnit = '|'
separator = '+' 

for cd in cursor.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 results:
    print(tavnit % row)
print(separator)

这是输出:

+--------+---------+---------------+------------+------------+
| ip_log | user_id | type_id       | ip_address | time_stamp |
+--------+---------+---------------+------------+------------+
| 227    | 1       | session_login | 10.0.0.2   | 1358760386 |
| 140    | 1       | session_login | 10.0.0.2   | 1358321825 |
| 98     | 1       | session_login | 10.0.0.2   | 1358157588 |
+--------+---------+---------------+------------+------------+

神奇之处在于每个cursor.description行的第三列(代码中称为cd[2])。此列表示最长值的字符长度。因此,我们将显示的列的大小设置为它与列标题本身的长度(max(cd[2], len(cd[0])))之间的较大值。

答案 1 :(得分:12)

使用prettytable

x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"])
x.set_field_align("City name", "l") # Left align city names
x.set_padding_width(1) # One space between column edges and contents (default)
x.add_row(["Adelaide",1295, 1158259, 600.5])
x.add_row(["Brisbane",5905, 1857594, 1146.4])
x.add_row(["Darwin", 112, 120900, 1714.7])
x.add_row(["Hobart", 1357, 205556, 619.5])
x.add_row(["Sydney", 2058, 4336374, 1214.8])
x.add_row(["Melbourne", 1566, 3806092, 646.9])
x.add_row(["Perth", 5386, 1554769, 869.4])
print x

+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
| Adelaide  | 1295 |  1158259   |      600.5      |
| Brisbane  | 5905 |  1857594   |      1146.4     |
| Darwin    | 112  |   120900   |      1714.7     |
| Hobart    | 1357 |   205556   |      619.5      |
| Sydney    | 2058 |  4336374   |      1214.8     |
| Melbourne | 1566 |  3806092   |      646.9      |
| Perth     | 5386 |  1554769   |      869.4      |
+-----------+------+------------+-----------------+

答案 2 :(得分:2)

使用Python库tabulate将MySQL结果打印为MySQL Table格式的最佳,最简便的方法

user@system$ pip install tabulate

Python代码:

import mysql.connector
from tabulate import tabulate

mydb = mysql.connector.connect(
                host="localhost",
                user="root",
                passwd="password",
                database="testDB"
              )

mycursor = mydb.cursor()
mycursor.execute("SELECT emp_name, salary FROM emp_table")
myresult = mycursor.fetchall()


print(tabulate(myresult, headers=['EmpName', 'EmpSalary'], tablefmt='psql'))

输出:

user@system:~$ python python_mysql.py
+------------+-------------+
| EmpName    | EmpSalary   |
|------------+-------------|
| Ram        | 400         |
| Dipankar   | 100         |
| Santhosh   | 200         |
| Nirmal     | 470         |
| Santu      | 340         |
| Shiva      | 100         |
| Karthik    | 500         |
+------------+-------------+

答案 3 :(得分:1)

数据显示在某些列表中,并且正在打印标题。考虑一些这样的格式:

res = ['trebuchet ms', 8868, 417]
res = ['lucida sans unicode', 3525, 116]

print(' {0[0]:20s} {0[1]:10d} {0[2]:10d}'.format(res))

给你

 trebuchet ms               8868        417
 lucida sans unicode        3525        116

请注意,列表中的索引是在字符串内完成的,format只需要提供列表或元组。

或者,您可以以编程方式指定宽度:

wid1 = 20
wid2 = 10
wid3 = 10
print(' {:{}s} {:{}d} {:{}d}'.format(res[0], wid1, res[1], wid2, res[2], wid3))

,它提供与上面相同的输出。

您必须根据需要调整字段宽度,并在每个数据行的循环列表中循环,而不是组成样本行。数字自动右对齐,字符串自动离开。

对某些人来说,优势当然是这不依赖于任何外部库,并且完成了Python已经提供的功能。

答案 4 :(得分:1)

你需要做两遍:

  1. 计算列宽
  2. 打印表格
  3. 所以

    table = cur.fetchall()
    widths = [0]*len(table[0])  # Assuming there is always one row
    for row in table:
        widths = [max(w,len(c)) for w,c in zip(widths,row)]
    

    现在您可以轻松打印表格了。

    打印数字时请记住string.rjust方法。

    <强>更新

    计算widths的更实用的方法是:

    sizetable = [map(len,row) for row in table]
    widths = map(max, zip(*sizetable))