Flask Programming

Hands On No. 11 : CRUD Operations in MySQL

Resources

Source Code of hello.py
from flask import Flask
from flask import render_template
from flask import request
from sqlalchemy import create_engine
from sqlalchemy import text
engine = create_engine("mysql+mysqlconnector://dhruvin:cse123456@dhruvin.mysql.pythonanywhere-services.com:3306/dhruvin$dm", echo=True)

app = Flask(__name__, template_folder='templates')



@app.route('/')
def indexpage():
    return render_template('index.html')

@app.route('/viewdata')
def viewdata():
    with engine.connect() as conn:
        result = conn.execute(text("SELECT x,y FROM emp"))
        studentdata = []
        studentdata.append(['Student Id','Student Name'])
        for row in result:
            student = []
            student.append(row.x)
            student.append(row.y)
            print(f"Student No. : {row.x} Name : {row.y}")
            studentdata.append(student)
        print(student)
        print(studentdata)

    return render_template('View-Data.html', studentdata=studentdata)

Source Code of index.html

<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.4/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>

<div class="container">
<h2>&nbsp;</h2>
<h2>Enter Details</h2>

<form action="/savedata" method="POST">
<div class="form-group">
<label for="usr">Enter No :</label>
<input type="text" class="form-control" id="studentno" name="studentno">
</div>
<div class="form-group">
<label for="usr">Enter Name :</label>
<input type="text" class="form-control" id="studentname" name="studentname">
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>

</div>

</body>
</html>

Source Code of View-Data.html

<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
<h2>Student Data</h2>

<table class="table">

<tbody>
{% for temp in studentdata %}
<tr>
{% for t in temp %}
<td>{{ t }} </td>
{% endfor %}
</tr>
{% endfor %}


</tbody>
</table>
</div>

</body>
</html>