简体   繁体   English

使用Python sqlite3模块时的OperationalError

[英]OperationalError when using Python sqlite3 module

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: near "%": syntax error ventoryCurs.execute('''UPDATE table SET status ='Out of Stock'WHERE id =%s)''',i [0])OperationalError:near“%”:语法错误

Without seeing more of the code, it's difficult to fix the problem completely, but looking at your code, I think the problem might be the %s in this line: 如果看不到更多代码,很难完全解决问题,但是查看您的代码,我认为问题可能出在这行代码中的%s上:

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

According to the documentation for the SQLite module in both Python 2 and Python 3 , the sqlite3 module requires a ? 根据Python 2Python 3中 SQLite模块的文档, sqlite3模块需要一个? as a placeholder, not %s or some other format string. 作为占位符,而不是%s或其他格式的字符串。

According to the Python 2 documentation , a %s placeholder could be used like this: 根据Python 2文档可以这样使用%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)

but that's a simple format string, not actually the database's placeholder. 但这是一个简单的格式字符串,实际上不是数据库的占位符。 Also, as the comment shows, you should never build queries that way because it makes them vulnerable to SQL injection. 另外,如注释所示,永远不要以这种方式构建查询,因为它会使它们容易受到SQL注入的攻击。 Rather, you should build them like this, using a ? 相反,您应该使用?来像这样构建它们? instead: 代替:

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

The documentation has more details, but I believe that is the solution to the error you posted. 该文档有更多详细信息,但是我相信这是您所发布错误的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM