How to display data from MySQL in HTML table using Python

Theory of Computation
In this article, you will learn very simple code to fetch data from a MySQL database and display it in an HTML table using Python.
MySQL is the most popular and widely used Open Source Relational Database Management System. It can run on many different platforms without failure, even in a low-powered PC, and Python provides support to work with MySQL database. Programming in Python is considerably simple and efficient compared to other languages. It has a set of useful libraries and packages that minimize the use of code in our day-to-day life. Python needs a MySQL driver to access the MySQL database. Python provides various modules to access MySQL databases from a web server such as PyMySQL, mysql.connector, etc.
In this article, we have used the MySQL Connector module. The MySQL Connector module is written in pure Python and compatible with Python 3. It is self-sufficient to execute database queries through Python.
Suppose we have an "employee" table that contains an employee id, name, email and phone number. We want to display the employee's whole information on a web page in an HTML table.
CREATE TABLE IF NOT EXISTS `employee` (
  `emp_id` int(11) NOT NULL AUTO_INCREMENT,
  `emp_name` varchar(150) NOT NULL,
  `email` varchar(150) NOT NULL,
  `phone` varchar(100) NOT NULL,
  PRIMARY KEY (`emp_id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;

INSERT INTO `employee` (`emp_id`, `emp_name`, `email`, `phone`) VALUES
(1, 'John', 'john@example.com', '2323234543'),
(2, 'Smith', 'smith@example.com', '9898577442'),
(3, 'Priska', 'priska@example.com', '9393452387'),
(4, 'Gaga', 'gaga@example.com', '8482764537');
We need two modules for this application, webbrowser and mysql.connector. The webbrowser module is by default available with python package. We do not need to install this, but we need to install the mysql.connector module.
The installer requires 'python.exe' in your system PATH, otherwise it will fail to install. So make sure to add Python in your system environment. We can also install MySQL Connector using pip command.
pip install mysql-connector
As, this connector is already installed in my system. It returns the following -
c:\python37\Scripts>pip install mysql-connector
Requirement already satisfied: mysql-connector in c:\python37\lib\site-packages (2.2.9)
This is also a way to check the successful installation of MySQL connector.
First, we need to import both modules at the top of the script -
import mysql.connector
import webbrowser
Next, use the connect() constructor to create a connection to the MySQL server. Make sure to replace 'hostname', 'username', 'password' and 'database' with your database credentials and name.
conn = mysql.connector.connect(user='root', password='',
                              host='localhost',database='company')

if conn:
    print ("Connected Successfully")
else:
    print ("Connection Not Established")
Here, we have used the select query to fetch data. Next, we have iterated on the fetched data and stored it in a list variable in an HTML tabular format.
select_employee = """SELECT * FROM employee"""
cursor = conn.cursor()
cursor.execute(select_employee)
result = cursor.fetchall()

p = []

tbl = "IDNameEmailPhone"
p.append(tbl)

for row in result:
    a = "%s"%row[0]
    p.append(a)
    b = "%s"%row[1]
    p.append(b)
    c = "%s"%row[2]
    p.append(c)
    d = "%s"%row[3]
    p.append(d)
Next, we have created an HTML template and passed the above list variable.
contents = '''<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html; charset=ISO-8859-1"
http-equiv="content-type">
<title>Python Webbrowser</title>
</head>
<body>
<table>
%s
</table>
</body>
</html>
'''%(p)
The Python webbrowser module provides a feature to open a webpage in the browser. In the given code, we have created an HTML file and placed the above generated HTML content and rendered it in a web browser.
filename = 'webbrowser.html'

def main(contents, filename):
    output = open(filename,"w")
    output.write(contents)
    output.close()

main(contents, filename)    
webbrowser.open(filename)
Above, we have explained the code in chunks. Here we have merged all to get the complete code to display MySQL data in an HTML table using Python.
import mysql.connector
import webbrowser

conn = mysql.connector.connect(user='root', password='',
                              host='localhost',database='company')

if conn:
    print ("Connected Successfully")
else:
    print ("Connection Not Established")

select_employee = """SELECT * FROM employee"""
cursor = conn.cursor()
cursor.execute(select_employee)
result = cursor.fetchall()

p = []

tbl = "<tr><td>ID</td><td>Name</td><td>Email</td><td>Phone</td></tr>"
p.append(tbl)

for row in result:
    a = "<tr><td>%s</td>"%row[0]
    p.append(a)
    b = "<td>%s</td>"%row[1]
    p.append(b)
    c = "<td>%s</td>"%row[2]
    p.append(c)
    d = "<td>%s</td></tr>"%row[3]
    p.append(d)


contents = '''<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html; charset=ISO-8859-1"
http-equiv="content-type">
<title>Python Webbrowser</title>
</head>
<body>
<table>
%s
</table>
</body>
</html>
'''%(p)

filename = 'webbrowser.html'

def main(contents, filename):
    output = open(filename,"w")
    output.write(contents)
    output.close()

main(contents, filename)    
webbrowser.open(filename)

if(conn.is_connected()):
    cursor.close()
    conn.close()
    print("MySQL connection is closed.")    

Once you run the above code, it returns something like this in the browser.
  

Convert MySQL query result to JSON in Python
Insert XML Data to MySQL Table using Python
CRUD operations in Python using MYSQL Connector
Python Converting a CSV File to a MySQL Table
Get data from MySQL in Django View with Models
Insert data in MySQL database from an HTML form using Django
MongoDB CRUD operations Python Write DataFrame to csv Python Python Pandas Tutorial Pandas DataFrame example Python tkinter messagebox options Tkinter geometry window size Tkinter scale style Python Tkinter tutorial Python turtle graphics code Factorial program in Python with recursion Python code for snake game Python extract data from JSON file Python XML to dict ElementTree Python dict to XML attributes Python convert list to numpy array How to shuffle a list in Python Print hollow diamond pattern in Python Python *args **kwargs  

Jan 3
Stateful vs Stateless
A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...

A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...

Dec 29
Best programming language to learn in 2021
In this article, we have mentioned the analyzed results of the best programming language for 2021...

In this article, we have mentioned the analyzed results of the best programming language for 2021...

Dec 20
How is Python best for mobile app development?
Python has a set of useful Libraries and Packages that minimize the use of code...

Python has a set of useful Libraries and Packages that minimize the use of code...

July 18
Learn all about Emoji
In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...

In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...

Jan 10
Data Science Recruitment of Freshers
In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...

In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...






eTutorialsPoint©Copyright 2016-2022. All Rights Reserved.