如何在python中的sql中声明变量?
我试过这样的票价:
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()
输出:
---------------------------------------------------------------------------
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']
所以看起来当我到达底部的#3; 5时,我无法将列表放入我的sqldb 我怎样才能做到这一点 ? 我试图声明变量类型但它不起作用!
答案 0 :(得分:4)
c.execute('INSERT INTO imdb1 ( Title, Rating) values (?, ?)', (list[0],list[1]))
请注意,这是在格式化数据库字符串时应遵守的一般原则。使用格式错误的电影标题,用户可能会损坏您的数据库 1 (称为SQL injection)。
1 我不确定他们在这里可以造成多大的伤害,因为sqlite的执行只执行一个语句,但我确信其他人的经验可能超过我无论如何都要编造一些非常讨厌的东西。