0

Problem:

I have a problem with inserting data into SQlite with python. At this moment i am new to python so this must be beginner mistake.

Errors :

OperationalError: unrecognized token: "{"

What I have tried:

I have read many tutorials and tried many options as shown below in the code examples.But i cannot get this to work without error for some reason.

Some examples :

cursor.execute("INSERT INTO wanted_movie (tmdb_id, name, year) VALUES ({tmdb_id}, {name}, {year})".format(
        tmdb_id=str(data['id']), name=str(data['title']), year=str(data['release_date']).split('-')[0]))

cursor.execute("INSERT INTO wanted_movie (tmdb_id, name, year) VALUES ({tmdb_id}, {name}, {year})", {
        "tmdb_id": str(data['id']), "name": str(data['title']), "year": str(data['release_date']).split('-')[0]})
    conn.commit()

Question :

Can someone help me to insert a row correctly with SQlite3 in a pythonic way?

3
  • 1
    The specific error is missing the ** to unpack the dictionary in the second example. However, please read docs.python.org/2/library/sqlite3.html and don't use str.format to interpolate variables! Commented Feb 12, 2015 at 22:40
  • I read about 10 tutorials, but not the docs. Thanks Commented Feb 12, 2015 at 22:46
  • Add as answer please. So i can accept Commented Feb 12, 2015 at 22:48

1 Answer 1

5

More than a pythonic way there is a sqlitic way

From the docs

Instead, use the DB-API’s parameter substitution. Put ? as a placeholder wherever you want to use a value, and then provide a tuple of values as the second argument to the cursor’s execute() method.

One of your examples can be solved by using

values = (data['id'],data['title'],data['release_date'])
cursor.execute("INSERT INTO wanted_movie (tmdb_id, name, year) VALUES (?, ?, ?)",values)
Sign up to request clarification or add additional context in comments.

1 Comment

As the Python Database API Specification v2.0 mentions, the ? placeholder can also be found out from the module's paramstyle global, i.e. sqlite3.paramstyle is 'qmark'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.