Print results in MySQL format with Python
Best and easiest way to print MySQL results into MySQL Table format using Python Library tabulate
user@system$ pip install tabulate
Python Code:
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'))
Output:
user@system:~$ python python_mysql.py
+------------+-------------+
| EmpName | EmpSalary |
|------------+-------------|
| Ram | 400 |
| Dipankar | 100 |
| Santhosh | 200 |
| Nirmal | 470 |
| Santu | 340 |
| Shiva | 100 |
| Karthik | 500 |
+------------+-------------+
You need to do two passes:
- Calculate the column widths
- Print the table
So
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)]
Now you can print the table trivially.
Remember the string.rjust
method when printing the numbers.
Update
A more functional way of calculating widths
is:
sizetable = [map(len,row) for row in table]
widths = map(max, zip(*sizetable))
Use 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 |
+-----------+------+------------+-----------------+
There is no need for an external library. The prints out the data with the column names. All lines with the 'columns' variable can be eliminated if you do not need the column names.
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)
This is the output:
+--------+---------+---------------+------------+------------+
| 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 |
+--------+---------+---------------+------------+------------+
The magic lies in the third column of each cursor.description
line (called cd[2]
in the code). This column represents the length in characters of the longest value. Thus we size the displayed column as the greater between that and the length of the column header itself (max(cd[2], len(cd[0]))
).