Display MySQL Table Content in Python

Python MySQL | Display Table Content: In this tutorial, we will learn how to display MySQL table content with the help of Python program? By Shivang Yadav Last updated : April 21, 2023

Python programming language is a high-level and object-oriented programming language developed by Guido Van Rossum, when he was working at CWI (Centrum Wiskunde & Informatica) which is a National Research Institute for Mathematics and Computer Science in the Netherlands.

In this era of machine learning and AI, the language has become so versatile that it can be used for performing multiple tasks. And backend development is one of them.

Using Python, we can access and manipulate databases and perform other backend tasks. Python has a library named pymysql to perform the MySQL task and execute the queries.

We need to access the database using Python and then get the content of the table we have created in here, create an SQL table.

And then we will print the content of this table on screen.

How to Display MySQL Table Content in Python?

Steps to display content of table in python:

  1. Inmport the MySQL connect using import statement.
    import  pymysql as ps
  2. Connect to database using connect() method.
    cn=ps.connect(host='localhost',port=3306,user='root',password='123',db='tata')
  3. Create a command to execute the query using cursor() method.
    query="select * from products"
  4. Execute the command using the execute() method.
    cmd.execute(query)
  5. And, then we have used the fetchAll() method which is stored in rows.
     rows=cmd.fetchall()
  6. Print all elements of rows.

Python program to display MySQL table content

import  pymysql as ps

try:
    cn=ps.connect(host='localhost',port=3306,user='root',password='123',db='tata')
    
    cmd=cn.cursor()
    
    query="select * from products"
    
    cmd.execute(query)
    
    rows=cmd.fetchall()
    
    # print(rows)
    for row in rows:
        for col in row:
            print(col,end=' ')
        print()
    
    cn.close()

except Exception as e:
    print(e)

Output

001 macBook Pro 120000 2020
002 iPad Pro 75000 2020

Python MySQL Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.