使用Python以MySQL格式打印结果
以MySQL使用Python在控制台中打印MySQL查询结果的相同方式打印MySQL查询结果的最简单方法是什么?例如,我想得到这样的东西:使用Python以MySQL格式打印结果,python,mysql,Python,Mysql,以MySQL使用Python在控制台中打印MySQL查询结果的相同方式打印MySQL查询结果的最简单方法是什么?例如,我想得到这样的东西: +---------------------+-----------+---------+ | font | documents | domains | +---------------------+-----------+---------+ | arial | 99854 | 574
+---------------------+-----------+---------+
| 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;
但由于宽度不同,此代码会产生混乱的输出。数据似乎在某个列表中,并且正在打印标题。考虑一下这样的格式:
res = ['trebuchet ms', 8868, 417]
res = ['lucida sans unicode', 3525, 116]
及
给你
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已经提供的功能完成的
了解有关字符串格式设置的详细信息
你需要做两次传球:
string.rjust
方法
更新
计算宽度的更实用的方法是:
sizetable = [map(len,row) for row in table]
widths = map(max, zip(*sizetable))
不需要外部库。打印出带有列名的数据。如果不需要列名,则可以删除包含“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 |
+--------+---------+---------------+------------+------------+
神奇之处在于每个光标的第三列。description
行(代码中称为cd[2]
)。此列表示最长值的长度(以字符为单位)。因此,我们将显示列的大小设置为与列标题本身长度之间的较大值(max(cd[2],len(cd[0]))
。使用Python库制表将MySQL结果打印成MySQL表格式的最佳且最简单的方法
user@system$pip安装表格
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 |
+------------+-------------+
输出:
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 |
+------------+-------------+
您能为我们提供一些示例输入以显示输出吗?您使用哪个Python模块与数据库交互?它是否符合Python数据库API v2.0(PEP249?)?i、 e.它是否以列表的形式返回查询结果?@Ben我使用MySQLdb
,我使用光标执行查询,然后使用fetchall
(我相信这是一个生成器)。每个结果项都是一个元组。可能是你正在寻找的,我不知道这个第三方库。。谢谢看起来很有用。有两件事可能会帮助尝试使用psycopg的人:首先,cd[2]
的值通常不使用psycopg设置,因此要获得列的最大长度,可以执行类似于max\u colu length=max(list(map(lambda x:len(str(x[index])、results))
的操作,然后是max(max\u col length,len(cd[0])
。其次,如果您想截断列文本的长度并填充它,您可以用tavnit+=“%-”+%ss |“%(w,)
替换为tavnit+=“%-”+“%s.%ss |“%(w,w)
获取所有字段名,如mycursor中i的字段名=[i[0]。description]print(制表(myresult,headers=字段名,tablefmt='psql'))
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 |
+------------+-------------+