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.
    Python Project
  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.
    Web Project
  4. You need to Install the 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.
    Python Environment
  2. Select pip from the dropdown and search for pypyodbc, as shown below.
    PIP
  3. After installing pypyodbc package, the message is shown below in the output Window, which indicates you installed it successfully.
    Message
  4. As shown below, the pypyodbc is added to your Python environment.
     Python

To retrieve the data from the table, use the cursor.execute() method.

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

To view the command, refer to the screenshot mentioned below.

Command

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.

 Web Browser

Note. The password may differ, which is based on your SQL server user.

The final code is given below.

from datetime import datetime
from flask import render_template, redirect, request
from FlaskWebProject7 import app
import pypyodbc
# creating connection Object which will contain SQL Server Connection
connection = pypyodbc.connect('Driver={SQL Server};Server=.;Database=Employee;uid=sa;pwd=sA1234')  # Creating Cursor
cursor = connection.cursor()
cursor.execute("SELECT * FROM EmployeeMaster")
s = "<table style='border:1px solid red'>"
for row in cursor:
    s = s + "<tr>"
    for x in row:
        s = s + "<td>" + str(x) + "</td>"
    s = s + "</tr>"
connection.close()
@app.route('/')
@app.route('/home')
def home():
    return "<html><body>" + s + "</body></html>"

SQL Server

Run the project and the output is as shown below.

Run

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.


Recommended Free Ebook
Similar Articles