from flask import render_template, request

import sqlite3
def index():

    return render_template('index.html')


def addrec():
    if request.method == 'POST':
        try:
            nm = request.form['nm']
            addr = request.form['add']
            city = request.form['city']
            pin = request.form['pin']

            with sqlite3.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("response.html", msg=msg)
            con.close()


def list():
    con = sqlite3.connect("database.db")
    con.row_factory = sqlite3.Row

    cur = con.cursor()
    cur.execute("select * from students")

    rows = cur.fetchall()
    print(rows)
    for row in rows:
        print(row)
    return render_template("list.html", rows=rows)
