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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.