【问题标题】:OperationalError when using Python sqlite3 module使用 Python sqlite3 模块时出现 OperationalError
【发布时间】:2012-07-15 00:10:12
【问题描述】:
def StatusUpdate(self, table):
    inventoryCurs.execute('SELECT * from Table')
    for i in inventoryCurs:
        html = urlopen(i[5]).read()
        Soup = BeautifulSoup(html)

        if table.StockStatus(Soup) == 'Out of Stock':        
            inventoryCurs.execute('''UPDATE table SET status = 'Out of Stock' WHERE id = %s)''', i[0])

inventoryCurs.execute('''UPDATE table SET status = 'Out of Stock' WHERE id = %s)''', i[0]) OperationalError:“%”附近:语法错误

【问题讨论】:

    标签: python sqlite


    【解决方案1】:

    没有看到更多的代码,很难完全解决问题,但是看你的代码,我认为问题可能是这行中的%s

    inventoryCurs.execute('''UPDATE table SET status = 'Out of Stock' WHERE id = %s)''', i[0])
    

    根据Python 2Python 3 中SQLite 模块的文档,sqlite3 模块需要? 作为占位符,而不是%s 或其他格式字符串。

    根据Python 2 documentation%s 占位符可以这样使用:

    import sqlite3
    conn = sqlite3.connect('example.db')
    c = conn.cursor()
    # Never do this -- insecure!
    symbol = 'IBM'
    c.execute("select * from stocks where symbol = '%s'" % symbol)
    

    但这是一个简单的格式字符串,实际上并不是数据库的占位符。此外,正如评论所示,您永远不应该以这种方式构建查询,因为这会使它们容易受到 SQL 注入的攻击。相反,您应该像这样构建它们,而是使用?

    import sqlite3
    conn = sqlite3.connect('example.db')
    c = conn.cursor()
    # Do this instead
    t = (symbol,)
    c.execute('SELECT * FROM stocks WHERE symbol=?', t)
    

    文档有更多详细信息,但我相信这是您发布的错误的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-12
      • 2020-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多