How to Print Out All Rows of a MySQL Table in Python?

How to Print Out All Rows of a MySQL Table in Python?

To print out all rows of a MySQL table in Python, you can use the mysql-connector-python library. Here's a step-by-step guide to achieve this:

Step 1: Install the library

If you haven't already, you need to install mysql-connector-python:

pip install mysql-connector-python 

Step 2: Write the Python script

import mysql.connector # Establish a connection to the MySQL database conn = mysql.connector.connect( host="YOUR_HOST", # usually "localhost" for local databases user="YOUR_USERNAME", password="YOUR_PASSWORD", database="YOUR_DATABASE_NAME" ) # Create a cursor object to interact with the MySQL server cursor = conn.cursor() # Query to fetch all rows from the table query = "SELECT * FROM YOUR_TABLE_NAME" cursor.execute(query) # Fetch and print all rows from the table rows = cursor.fetchall() for row in rows: print(row) # Close the cursor and the connection cursor.close() conn.close() 

Replace the placeholders (YOUR_HOST, YOUR_USERNAME, YOUR_PASSWORD, YOUR_DATABASE_NAME, and YOUR_TABLE_NAME) with the appropriate values for your MySQL setup.

Running the script will print out all the rows from the specified MySQL table.

Note: Make sure you handle exceptions and errors appropriately in a real-world application, especially when dealing with database operations. The above code is a basic example for demonstration purposes.


More Tags

pageable count-unique excel-2003 simulate spring-tool-suite django-database eclipselink roles access-keys lytebox

More Programming Guides

Other Guides

More Programming Examples