Python + SQLite + Flask Full Notes with HTML Form Integration
1. Connecting to SQLite in Python
---------------------------------
import sqlite3
conn = sqlite3.connect("mydatabase.db")
cursor = conn.cursor()
# Create a table
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER NOT NULL
''')
conn.commit()
conn.close()
2. Creating a Flask Web Application
-----------------------------------
from flask import Flask, request, render_template
import sqlite3
app = Flask(__name__)
# Function to connect to database
def get_db_connection():
conn = sqlite3.connect('mydatabase.db')
conn.row_factory = sqlite3.Row
return conn
3. Creating a Simple HTML Form (save as 'templates/form.html')
--------------------------------------------------------------
<html>
<body>
<h2>Add User</h2>
<form action="/add_user" method="post">
Name: <input type="text" name="name"><br><br>
Age: <input type="number" name="age"><br><br>
<input type="submit" value="Submit">
</form>
<br>
<a href="/users">View All Users</a>
</body>
</html>
4. Route to Display the Form
----------------------------
@app.route('/')
def form():
return render_template('form.html')
5. Route to Handle Form Submission and Store in SQLite
------------------------------------------------------
@app.route('/add_user', methods=['POST'])
def add_user():
name = request.form['name']
age = request.form['age']
conn = get_db_connection()
conn.execute("INSERT INTO users (name, age) VALUES (?, ?)", (name, age))
conn.commit()
conn.close()
return "User added successfully! <a href='/'>Add Another</a>"
6. Route to View All Data in a Table
------------------------------------
@app.route('/users')
def users():
conn = get_db_connection()
rows = conn.execute("SELECT * FROM users").fetchall()
conn.close()
html = "<h2>All Users</h2><table border='1'><tr><th>ID</th><th>Name</th><th>Age</th></tr>"
for row in rows:
html += f"<tr><td>{row['id']}</td><td>{row['name']}</td><td>{row['age']}</td></tr>"
html += "</table><br><a href='/'>Back to Form</a>"
return html
7. Running the Flask App
------------------------
if __name__ == '__main__':
app.run(debug=True)
Explanation:
------------
- You create an SQLite database using `sqlite3.connect()`.
- Use Flask to handle web routes and show HTML forms.
- The HTML form sends data to Flask via POST.
- Flask takes that form data and inserts it into SQLite.
- You can view the stored data in an HTML table using another Flask route.
Make sure you have a 'templates' folder in the same directory as your Python file. Inside it, save the
form.html file.