What is the easiest way to print the result from MySQL query in the same way MySQL print them in the console using Python? For example I would like to get something like tha
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 |
+------------+-------------+