How to Print Out All Rows of a MySQL Table in Python?
MySQL server is an open-source relational database management system which is a major support for web-based applications. Databases and related tables are the main component of many websites and applications as the data is stored and exchanged over the web. In order to access MySQL databases from a web server(here XAMPP) we use various modules in Python such as PyMySQL, mysql.connector, etc.
In this article, we will see how to get the all rows of a MySQL table by making a database connection between python and MySQL.
First, we are going to connect to a database having a MySQL table. The SQL query to be used to get all the rows:
SELECT * FROM table-name
Finally, after getting all the rows, display each row in the table using an iterator.
Below are some programs which depict how to extract rows from a MySQL table in a Database:
Example 1:
Below is the table geeksdemo is database geek which is going to be accessed by a Python script:
Below is the program to get all the rows in an MYSQL table:
Python3
import pymysql
pymysql.install_as_MySQLdb()
import MySQLdb
db = MySQLdb.connect( "localhost" , "root" , " ", " GEEK")
cursor = db.cursor()
cursor.execute( "SELECT * FROM geeksdemo" )
result = cursor.fetchall()
for row in result:
print (row)
print ( "\n" )
|
Output:
Example 2:
Here is another example to extracts all the rows from a table in a given database, below is the table scheme and rows:
Below is the Python script extract all each row from the table:
Python3
import MySQLdb
import pymysql
pymysql.install_as_MySQLdb()
db = MySQLdb.connect( "localhost" , "root" , " ", " techgeeks")
cursor = db.cursor()
cursor.execute( "SELECT * FROM techcompanies" )
result = cursor.fetchall()
for row in result:
print (row, '\n' )
|
Output:
Last Updated :
26 Nov, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...