【问题标题】:Declare varchar in python在 python 中声明 varchar
【发布时间】:2014-05-09 20:00:22
【问题描述】:

如何在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”时,我无法将列表放入我的 sqldb 我怎样才能做到这一点 ? 我试图声明变量类型,但它不起作用!

【问题讨论】:

    标签: python sql variables declare


    【解决方案1】:

    问题是您替换的字符串有引号。与其使用 python 的字符串格式,不如使用 sqlite 的:

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

    请注意,这是您在为数据库格式化字符串时应遵守的一般原则。使用恶意格式的电影标题,用户可能会损坏您的数据库1(称为SQL injection)。

    1我不确定他们在这里能造成多大的破坏,因为 sqlite 的 execute 只执行一个语句,但我确信其他人比我更有经验不管怎样,编造一些非常讨厌的东西。

    【讨论】:

    • 我不认为你想要引号围绕?字符。
    • @DanielRoseman -- 可能不会。我从来没有使用过 sqlite,但我最近决定我应该尝试学习一些关于数据库等的东西。在这里回答问题是我学习如何实际正确操作的捷径;-)
    • 它有效:D 可以帮助我生成它现在说没有的 ROWID 吗?
    • @StevenRumbalski -- 更新时提到了 sql 注入。
    • @user3322871:声明rowid 类型为INTEGER PRIMARY KEY 而不是INT,它将自动递增。 docs 的浏览表明您甚至不需要声明 rowid,因为它是隐式维护的。 (最好将您的后续问题作为一个单独的问题提出。如果将来访问 stackoverflow 的访问者有类似的问题,它可以更好地找到问题。作为奖励,您还将获得毫无意义的互联网积分。问题。)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    • 2010-11-01
    相关资源
    最近更新 更多