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.

cursor = connection.cursor()
cursor.execute = ("select * from EmployeeMaster")

To view the 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  
  2. import datetime  
  3. from flask  
  4. import render_template  
  5. from FlaskWebProject7  
  6. import app  
  7.   
  8. import pypyodbc  
  9.   
  10. from datetime  
  11. import datetime  
  12.   
  13. from flask  
  14. import render_template, redirect, request  
  15.  
  16.  
  17.  
  18. # creating connection Object which will contain SQL Server Connection  
  19. connection = pypyodbc.connect('Driver={SQL Server};Server=.;Database=Employee;uid=sa;pwd=sA1234')# Creating Cursor  
  20.   
  21. cursor = connection.cursor()  
  22. cursor.execute("SELECT * FROM EmployeeMaster")  
  23. s = "<table style='border:1px solid red'>"  
  24. for row in cursor:  
  25.     s = s + "<tr>"  
  26. for x in row:  
  27.     s = s + "<td>" + str(x) + "</td>"  
  28. s = s + "</tr>"  
  29.   
  30.   
  31. connection.close()  
  32.   
  33. @app.route('/')  
  34. @app.route('/home')  
  35. def home():  
  36.   
  37.     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.

 

Up Next
    Ebook Download
    View all
    Learn
    View all