1

When I insert in DB, I get this error:

sqlite3.OperationalError: near "word": syntax error

Code:

con = sqlite3.connect('films.db')
cur = con.cursor()
cur.execute('CREATE TABLE films (id INTEGER PRIMARY KEY, name VARCHAR(100), ' +
            'img BLOB, imbd VARCHAR(30), country_year VARCHAR(50))')
con.commit()

for i in range(97):
    cur.execute('INSERT INTO films (name, img, imbd) VALUES(' + names[i].text_content() + ', ' + str(urllib.request.urlopen(img[i].get('src')).read()) + ', ' + imbd[i].text_content() + ' )')
    con.commit()
    print(cur.lastrowid)

This string "word" from "name".

How can I fix it?

1 Answer 1

2

The primary mistake which you are doing is that you are not enclosing the literals in quotations

con = sqlite3.connect('films.db')
cur = con.cursor()
cur.execute('CREATE TABLE films (id INTEGER PRIMARY KEY, name VARCHAR(100), ' +
            'img BLOB, imbd VARCHAR(30), country_year VARCHAR(50))')
con.commit()

for i in range(97):
    cur.execute('INSERT INTO films (name, img, imbd) VALUES("' + names[i].text_content() + '", "' + str(urllib.request.urlopen(img[i].get('src')).read()) + '", "' + imbd[i].text_content() + '" )')
    con.commit()
    print(cur.lastrowid)

But if you do like this you are doing the greatest error on earth. The insert statement should instead be

cur.execute('INSERT INTO films (name, img, imbd) VALUES(?,?,?)', (names[i].text_content(), str(urllib.request.urlopen(img[i].get('src')).read()), imbd[i].text_content()))

Else you are susceptable for SQL Syringing. Read this for description as to why you have to use ? instead of concatenation.

Finally See this picture and try to comprehend what would have gone wrong. enter image description here

Sign up to request clarification or add additional context in comments.

Comments

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.