在Python中声明varchar

0 投票
1 回答
9189 浏览
提问于 2025-04-18 06:02

我该如何在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']

看起来当我到达底部的“5”时,我无法把这个列表放入我的SQL数据库中。我该怎么做呢?我尝试过声明变量类型,但没有成功!

1 个回答

4

问题在于你要替换的字符串里有引号。与其使用Python的字符串格式化,不如直接用SQLite的格式。

c.execute('INSERT INTO imdb1 ( Title, Rating) values (?, ?)', (list[0],list[1]))

请注意,这是一条通用原则,在为数据库格式化字符串时应该遵循。因为如果用户输入了恶意格式的电影标题,可能会导致你的数据库被破坏1(这叫做SQL注入)。

1我不太确定他们能造成多大的损害,因为SQLite的执行只会执行一条语句,但我相信那些经验丰富的人可能会想出一些相当糟糕的事情。

撰写回答