Create Python Flask Web Application And Display SQL Records In Browser

Introduction

 
The example shown below exhibits how to create a Python Flask web application and display SQL Server table records in a Web Browser.
 
Steps
 
First, we will create a Flask Web Python project.
  1. Open Visual Studio.
  2. Select File, New, and then Project.
     
    C#
     
  3. Now, select Python followed by Flask Web Project, enter a name to the project and choose the location, where you want to save your project and then press OK.
     
    C# 
     
  4. You need to Install Python package for SQL Server Connectivity.
You need to install the packages for connecting SQL Server. To install the package, do the steps, as mentioned below.
  1. Right click on Python Environment, as shown below.
     
    C#
      
  2. Select pip from the dropdown and search for pypyodbc, as shown below.
      
    C#
     
  3. After installing pypyodbc package, the message is shown below in the output Window, which indicates you installed it successfully. 
     
    C#
      
  4. As shown below, the pypyodbc is added to your Python environment. 
     
    C#
To retrieve the data from the table, use cursor.execute() method.
  1. cursor = connection.cursor()  
  2. cursor.execute = ("select * from EmployeeMaster")  
To view the command, refer to the screenshot mentioned below.
 
C#
 
To retrieve the data from the database and show table records in the Web Browser, use HTML tags and then return it as the code, mentioned below.
 
C#
 
Note
 
The password may differ, which is based on your SQL server user.
 
The final code is given below.
  1. from datetime import datetime    
  2. from flask import render_template    
  3. from FlaskWebProject7 import app    
  4. import pypyodbc      
  5. from datetime import datetime    
  6.     
  7. from flask import render_template, redirect, request    
  8.    
  9. # creating connection Object which will contain SQL Server Connection    
  10. connection = pypyodbc.connect('Driver={SQL Server};Server=.;Database=Employee;uid=sa;pwd=sA1234')# Creating Cursor    
  11.     
  12. cursor = connection.cursor()    
  13. cursor.execute("SELECT * FROM EmployeeMaster")    
  14. s = "<table style='border:1px solid red'>"    
  15. for row in cursor:    
  16.     s = s + "<tr>"    
  17. for x in row:    
  18.     s = s + "<td>" + str(x) + "</td>"    
  19. s = s + "</tr>"    
  20. connection.close()    
  21.    
  22. @app.route('/')    
  23. @app.route('/home')    
  24. def home():    
  25.     
  26.     return "<html><body>" + s + "</body></html>"    
C#
 
Run the project and the output is as shown below.
 
C#
 
I hope you have learned how to connect to SQL Server and retrieve the table records with the Python Web Application named Flask and show the records in a Web Browser instead of the console.


Similar Articles