0

I have folder which contains app.py and books.db file now I want to insert values to that db file using flask.

I am able to read it properly but unable to insert values into it.

Any idea how to achieve this ?

@app.route('/insert',methods=['GET','POST'])
def addv():
    conn = sqlite3.connect('books.db')
    conn.row_factory = dict_factory
    cur = conn.cursor()
    cur.execute('insert into books values (NULL,2014,\'Vivank\',\'try\',\'trying\')')
    return "inserted"

This is not inserting values in books.db ?

Or any way around to insert data into it ?

Mansi Shukla
  • 377
  • 3
  • 23
  • What do you mean, achieve _this_ (and then show something that looks like a solution)? What's wrong with it (besides hardcoding strings in SQL)? – Amadan Feb 08 '19 at 05:17
  • I am unable to insert data in books.db file using python @Amadan – Mansi Shukla Feb 08 '19 at 05:34
  • I mean, what happens when you run the code you posted? Is there an error? Which one? Do you get "inserted" returned or not? Do your curtains burst into flames? – Amadan Feb 08 '19 at 05:39
  • I got returned but when I view books.db my inserted data is not showing up @Amadan – Mansi Shukla Feb 08 '19 at 05:39
  • 2
    Try `conn.commit()`? If the row is updated without an error but not saved, that's probably the only thing missing. – Amadan Feb 08 '19 at 05:40
  • 2
    using `flask-sqlalchemy` is better idea than doing direct insertion – sahasrara62 Feb 08 '19 at 05:44

1 Answers1

3

You could change your code to something like:

@app.route('/insert', methods=['GET','POST'])
def addv():
    if request.method == "POST";
        conn = sqlite3.connect('books.db')
        data = [None, 2014, 'Vivank', 'try', 'trying']
        conn.execute('insert into books values (?, ?, ?, ?, ?)', (*data,))
        conn.commit()
        return "inserted"
    return "Testing insert"
kellymandem
  • 1,709
  • 3
  • 17
  • 27