Python has built-in support for SQLite. The SQlite3 module comes with the Python release. In this article you will learn ho w the Flask application interacts with SQLite.
SQLite is a relational database system that uses the SQL query language to interact with the database. Each database can have tables and each table can have records.
The SQLite database storse all data in a single file. You can create an SQLite database from Python code. The program creates a SQLite database ‘database.db ‘ where the student tables are created.
As can be seen, the form data is published to the ‘/addrec’ URL of the binding addrec () function.
The addrec () function retrieves the form’s data through the POST method and inserts the student table.The message corresponding to the success or error in the insert operation will be rendered as ‘result.html’.
@app.route('/addrec',methods = ['POST', 'GET']) defaddrec(): if request.method == 'POST': try: nm = request.form['nm'] addr = request.form['add'] city = request.form['city'] pin = request.form['pin'] with sql.connect("database.db") as con: cur = con.cursor() cur.execute("INSERT INTO students (name,addr,city,pin) VALUES (?,?,?,?)",(nm,addr,city,pin) ) con.commit() msg = "Record successfully added" except: con.rollback() msg = "error in insert operation" finally: return render_template("result.html",msg = msg) con.close()
The HTML script for result.html contains an escape statement , which displays the result of the Insert operation.
1 2 3 4 5 6 7 8 9
<!doctype html> <html> <body> result of addition : {{ msg }} <h2><ahref = "\">go back to home page</a></h2> </body> </html>
List items
The application contains another list () function represented by the ‘/list’ URL.It populates’rows’ as a Multidict object that contains all records in the student table.This object is passed to the list.html template.
1 2 3 4 5 6 7 8 9 10
@app.route('/list') deflist(): con = sql.connect("database.db") con.row_factory = sql.Row cur = con.cursor() cur.execute("select * from students") rows = cur.fetchall(); return render_template("list.html",rows = rows)