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 ?

6
  • 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)? Commented Feb 8, 2019 at 5:17
  • I am unable to insert data in books.db file using python @Amadan Commented Feb 8, 2019 at 5: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? Commented Feb 8, 2019 at 5:39
  • 2
    Try conn.commit()? If the row is updated without an error but not saved, that's probably the only thing missing. Commented Feb 8, 2019 at 5:40
  • 2
    using flask-sqlalchemy is better idea than doing direct insertion Commented Feb 8, 2019 at 5:44

1 Answer 1

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"
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.