Reputation: 155
How can i declare a variable in sql in python ?
I have tried this so fare:
import re
import sqlite3
conn = sqlite3.connect('imdb1.db')
c = conn.cursor()
c.execute('''CREATE TABLE imdb1 (ROWID int, Title varchar(40), Rating int)''')
x = open("ratings.list.txt","r")
movread = x.readlines()
x.close()
#s = raw_input('Search: ').lower()
for ns in movread:
if 'the lord of the' in ns.lower():
d = re.split('\s+',ns,4)
Title = d[4].rstrip()
Rating= d[3]
list = [Title,Rating]
print list
# Insert a row of data
c.execute('INSERT INTO imdb1 ( Title, Rating) values ("%s","%s")'%(list[0],list[1]))
conn.commit()
Output:
---------------------------------------------------------------------------
OperationalError Traceback (most recent call last)
<ipython-input-90-0d9cfec4960a> in <module>()
25 print list
26 # Insert a row of data
---> 27 c.execute('INSERT INTO imdb1 ( Title, Rating) values ("%s","%s")'%(list[0],list[1]))
28 conn.commit()
29
OperationalError: near "5": syntax error
['The Lord of the Rings: The Return of the King (2003)', '8.9']
['The Lord of the Rings: The Fellowship of the Ring (2001)', '8.8']
['The Lord of the Rings: The Two Towers (2002)', '8.7']
['"5 Second Movies" (2007) {The Lord of the Rings and the Two Towers (#1.63)}', '6.2']
So it looks like when i reach "5 in the bottom, i cant put the list into my sqldb How can i do that ? I have tried to declare variable type but it did not work!
Upvotes: 0
Views: 10082
Reputation: 310019
the problem is that the string your substituting in has quotes. Rather than using python's string formatting, you should probably use sqlite's:
c.execute('INSERT INTO imdb1 ( Title, Rating) values (?, ?)', (list[0],list[1]))
Note that this is a general principle that you should abide by when formatting strings for a database. With a maliciously formatted movie title, a user could potentially corrupt your database1 (known as SQL injection).
1I'm not really sure how much damage they could do here as sqlite's execute only executes a single statement, but I'm sure that others with more experience than I could probably concoct some pretty nasty things regardless.
Upvotes: 4