<p>这更多的是SQL查询,而不是Python,但我还是会尝试回答:
(我没有使用过MySQL,但使用过PostgreSQL,所以这里对事物的解释可能略有不同)。</p>
<p>当你这么做的时候</p>
<pre><code>cursor.execute('select barcode from fridge where amount < quantity')
db.commit()
row = cursor.fetchall()
</code></pre>
<p>变量“row”现在是一个resultset(要理解:来自数据库的行列表)
类似于[(条形码1),(条形码2),(条形码3)…]</p>
<p>当您执行update语句时</p>
<pre><code>cursor.execute('update products set stock = 0 where barcode = %s', row)
</code></pre>
<p>这就变成了:</p>
<pre><code>update products set stock = 0 where barcode = [(barcode1), (barcode2), (barcode3)..]
</code></pre>
<p>这不是正确的SQL语句。</p>
<p>你应该这样做:</p>
<pre><code>cursor.execute('update products set stock = 0 where barcode in (%s)', ','.join([each[0] for each in row]))
</code></pre>
<p>或者更好的是,优化的东西:</p>
<pre><code>import MySQLdb
def order():
db = MySQLdb.connect(host='localhost', user='root', passwd='$$', db='fillmyfridge')
cursor = db.cursor()
cursor.execute('update products set stock = 0 where barcode in (select barcode from fridge where amount < quantity)')
db.commit()
</code></pre>
<p>好吧,要添加更多内容,在select查询之后而不是update查询之后有一个db.commit(),这是一个基本的错误。Select是等幂的,不需要提交,而Update需要提交。我强烈建议您在继续之前检查一些SQL。</p>