Print results in MySQL format with Python

前端 未结 5 521
-上瘾入骨i
-上瘾入骨i 2020-12-05 01:21

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

5条回答
  •  青春惊慌失措
    2020-12-05 01:35

    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         |
    +------------+-------------+
    

提交回复
热议问题